Uncaught in promise ошибка 400

I am using ReactJS, I want to create pagination for my application . When I click on next button I got this error Uncaught (in promise) Error: Request failed with status code 400 . I am fetching page data through API which were built in Loopback. Can someone please help me how to solve this problem because I am new and didn’t much know about ReactJS

Code

        class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Item: 5,
      skip: 0
    }

    this.handleClick = this.handleClick.bind(this);
  }

  urlParams() {
    return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
  }

  handleClick() {
    this.setState({skip: this.state.skip + 1})
  }

  render() {
    return (
      <div>
        <a href={this.urlParams()}>Example link</a>
        <pre>{this.urlParams()}</pre>
        <button onClick={this.handleClick}>Change link</button>
      </div>
    )
  }
}


ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))

asked Mar 12, 2019 at 21:15

Jon's user avatar

JonJon

3033 gold badges11 silver badges29 bronze badges

2

Your btnClick function:

btnClick(e) {
  const id = e.target.value;
  this.setState({
       id: id+1
    },
    () => this.getData()
  )
}

Is not going to work. e.target.value is undefined in a button and, when doing undefined + 1, you’ll receive an NaN.

I believe you want to retrieve the id from the state. Which would make your function like so:

btnClick(e) {
  const { id } = this.state;
  this.setState({
       id: id+1
    },
    () => this.getData()
  )
}

Or you might want to derive your setState call from your current state, like so (and I also removed the not needed arrow function declaration):

btnClick(e) {
  this.setState(({ id }) => ({
       id: id+1
    }),
    this.getData
  )
}

Finally, you could do a sanity check on your getData function to make sure that this.state.id is actually a number — you could use Number.isNaN().

answered Mar 12, 2019 at 22:00

Sergio Moura's user avatar

Sergio MouraSergio Moura

4,8491 gold badge21 silver badges38 bronze badges

1

Hi @spvjebaraj ,

My guess, that you have placed wrong field name into update object or mismatched list name.
getByTitle uses display names. Update and add objects should include only correct internal names with some exceptions for OData namings.

The errors in a console don’t give all the information. [400] Bad Reques can mean anything. Please check real response message in Chrome Dev Tools in Network tab or by a message within a catch.

OData error message will say more, e.g.:

{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The property 'Error' does not exist on type 'SP.Data.[ListName]ListItem'. Make sure to only use property names that are defined by the type."}}}

is a wrong set of field names

{"error":{"code":"-1, System.ArgumentException","message":{"lang":"en-US","value":"List '[Wrong lists' display name]' does not exist at site with URL 'http://....com/sites/site'."}}}

is a wrong lists’ display name

Also, there is no any need to wrap promise into another promise.
$pnp.sp.web.lists.getByTitle(listName).items.getById(itemId).update(fieldValue) is already return a promise. Your function can be:

var updateListItem = function(itemId, listName, fieldValue) {
  return $pnp.sp.web.lists
    .getByTitle(listName)
    .items.getById(itemId)
    .update(fieldValue);
};

To troubleshoot I would suggest:

  1. Check if the list name provided is correct:
var listName = '[your_list]';
$pnp.sp.web.lists.getByTitle(listName).then(console.log); 
// Should return list metadata, if not, then you're trying wrong name
  1. Check field internal names and that you provide corresponding data type format:
var listName = '[your_list]';
var itemId = [item_id];
$pnp.sp.web.lists.getByTitle(listName).items.getById(itemId ).get().then(console.log); 
// Check the list of possible basic fields 
// `WorkDescription` can be named something else, like `WorkDescription0`

I am trying to access a spring boot micro-service hosting on localhost but I am getting following error:

Uncaught (in promise) Error: Request failed with status code 400

Following is my code to access the service:

    import axios from "axios";

export const addProjectTask = (project_task, history) => async dispatch => {
  await axios.post("http://localhost:8080/api/board", project_task);
  history.push("/");
};

I have tried to search on the internet but I am not able to find any solution with the localhost. When I use the above URL in Postman it works fine so the URL is correct.

Edit:
Complete Error:

xhr.js:178 POST http://localhost:8080/api/board 400
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:61
Axios.<computed> @ Axios.js:86
wrap @ bind.js:9
(anonymous) @ projectTaskActions.js:4
(anonymous) @ index.js:8
(anonymous) @ redux.js:477
onSubmit @ AddProjectTask.js:31
callCallback @ react-dom.development.js:188
invokeGuardedCallbackDev @ react-dom.development.js:237
invokeGuardedCallback @ react-dom.development.js:292
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:306
executeDispatch @ react-dom.development.js:389
executeDispatchesInOrder @ react-dom.development.js:414
executeDispatchesAndRelease @ react-dom.development.js:3278
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:3287
forEachAccumulated @ react-dom.development.js:3259
runEventsInBatch @ react-dom.development.js:3304
runExtractedPluginEventsInBatch @ react-dom.development.js:3514
handleTopLevel @ react-dom.development.js:3558
batchedEventUpdates$1 @ react-dom.development.js:21871
batchedEventUpdates @ react-dom.development.js:795
dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3568
attemptToDispatchEvent @ react-dom.development.js:4267
dispatchEvent @ react-dom.development.js:4189
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
discreteUpdates$1 @ react-dom.development.js:21887
discreteUpdates @ react-dom.development.js:806
dispatchDiscreteEvent @ react-dom.development.js:4168

I am trying to access a spring boot micro-service hosting on localhost but I am getting following error:

Uncaught (in promise) Error: Request failed with status code 400

Following is my code to access the service:

    import axios from "axios";

export const addProjectTask = (project_task, history) => async dispatch => {
  await axios.post("http://localhost:8080/api/board", project_task);
  history.push("/");
};

I have tried to search on the internet but I am not able to find any solution with the localhost. When I use the above URL in Postman it works fine so the URL is correct.

Edit:
Complete Error:

xhr.js:178 POST http://localhost:8080/api/board 400
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:61
Axios.<computed> @ Axios.js:86
wrap @ bind.js:9
(anonymous) @ projectTaskActions.js:4
(anonymous) @ index.js:8
(anonymous) @ redux.js:477
onSubmit @ AddProjectTask.js:31
callCallback @ react-dom.development.js:188
invokeGuardedCallbackDev @ react-dom.development.js:237
invokeGuardedCallback @ react-dom.development.js:292
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:306
executeDispatch @ react-dom.development.js:389
executeDispatchesInOrder @ react-dom.development.js:414
executeDispatchesAndRelease @ react-dom.development.js:3278
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:3287
forEachAccumulated @ react-dom.development.js:3259
runEventsInBatch @ react-dom.development.js:3304
runExtractedPluginEventsInBatch @ react-dom.development.js:3514
handleTopLevel @ react-dom.development.js:3558
batchedEventUpdates$1 @ react-dom.development.js:21871
batchedEventUpdates @ react-dom.development.js:795
dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3568
attemptToDispatchEvent @ react-dom.development.js:4267
dispatchEvent @ react-dom.development.js:4189
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
discreteUpdates$1 @ react-dom.development.js:21887
discreteUpdates @ react-dom.development.js:806
dispatchDiscreteEvent @ react-dom.development.js:4168

Распознавание ошибок — обычное дело для программистов и веб-мастеров, самостоятельно прописывающих программные коды для своих ресурсов. Но порой с сообщением Error сталкиваются обычные пользователи, не имеющие даже приблизительного понятия о том, как быть в сложившейся ситуации. И возникает ступор: что делать? То ли свои действия исправлять, то ли вызывать специалистов, то ли технику уже на свалку везти?

Ошибка Uncaught (in promise) может появляться при работе с JavaScript, браузерами, приложениями и даже мессенджерами. Для понимания причины значение имеет характеристика конкретного сбоя, выводимая после Error.

В любом случае, это ошибка, возникшая в кодировке асинхронной операции с использованием функции обратного вызова. Снижая производительность кода до нуля, формально она не является критичной и, при распознавании, легко устраняется. Однако диагностировать причину бывает крайне трудоемко — именно на это указывает термин Uncaught (“необработанная”). И разобраться с возникающей проблемой по силам только грамотному и внимательному мастеру. Новичку же лучше обратиться за подсказкой к более опытным коллегам.

Для решения проблемы разработчику, как правило, предстоит вручную перебирать все варианты, которые способны вызвать несоответствие и сбой, устраняя конфликт между поставленной задачей и возможностью ее исполнения.

На практике промисы создаются как раз для того, чтобы перехватить ошибку, понять, на каком именно участке кода она возникает. Если бы не использовался Promise, команда просто оставалась бы без исполнения, а пользователь пребывал в неведении: почему та или иная функция не срабатывает? Очевидно, что информирование существенно упрощает задачу и сокращает время на реставрацию процесса.

При определении ошибки, перебирая цепочки, находят функцию, нарушающую логику. Ее обработка приводит к восстановлению работы системы. По сути, promise — это объект, не идущий в систему, а возвращающий в исходную точку сообщение о том, насколько удачно прошла операция. Если же произошел сбой — то какова его вероятная причина.

В то же время многократное использование промисов, связанное с ожиданием ответа, замедляет работу ресурса, утяжеляет его. Поэтому злоупотреблять удобной конструкцией не следует, как бы ни хотелось. Решение заключается в том, чтобы выбрать наиболее важный (или наиболее уязвимый) связующий блок, и именно на него установить необходимый код промис.

Работа по диагностике и обработке ошибок

Собственно, работа по диагностике и обработке ошибок, возникающих при создании сайтов, приложений или даже текстов в редакторе, почти всегда идет по тому же алгоритму: простым перебором исключаешь ошибочные варианты, один за другим.

Наглядный тому пример — поиск ответа на вопрос, почему перестали работать сочетания клавиш Ctrl+C и Ctrl+V. Комбинации “горячих клавиш” могут отказаться реагировать на нажатие из-за заражения вирусом, загрязнения клавиатуры, целого ряда других факторов. Тестируя их один за другим, раньше или позже непременно выйдешь на истинную причину — и тогда уже сможешь ее устранить.

Аналогично необходимо действовать при возникновении ошибки Uncaught (in promise): проверяя строчку за строчкой, каждый показатель, находить неверное значение, направляющее не туда, куда планировалось, переписывать его и добиваться намеченной цели.

Если вы не являетесь разработчиком, не создаете авторских приложений, не владеете профессиональным языком и никогда не касались даже близко программных кодов, но столкнулись с ошибкой Uncaught (in promise), прежде всего проверьте технику на присутствие вирусов. Запущенный злоумышленниками вредитель мог покалечить вашу систему в своих интересах. Второй шаг — попытка восстановления системы в точке, где она благополучно работала ранее. Вспомните, какие обновления вы устанавливали в последнюю очередь, попытайтесь избавиться от них. Если речь не идет о создаваемой вами авторской программе, избавиться от ошибки поможет переустановка поврежденного приложения. Если не поможет и это — остается обратиться к специалисту, способному исправить кодировку. При этом знайте, что проблема — не в “железе”, а в сбое используемого вами программного обеспечения.

Hi @spvjebaraj ,

My guess, that you have placed wrong field name into update object or mismatched list name.
getByTitle uses display names. Update and add objects should include only correct internal names with some exceptions for OData namings.

The errors in a console don’t give all the information. [400] Bad Reques can mean anything. Please check real response message in Chrome Dev Tools in Network tab or by a message within a catch.

OData error message will say more, e.g.:

{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The property 'Error' does not exist on type 'SP.Data.[ListName]ListItem'. Make sure to only use property names that are defined by the type."}}}

is a wrong set of field names

{"error":{"code":"-1, System.ArgumentException","message":{"lang":"en-US","value":"List '[Wrong lists' display name]' does not exist at site with URL 'http://....com/sites/site'."}}}

is a wrong lists’ display name

Also, there is no any need to wrap promise into another promise.
$pnp.sp.web.lists.getByTitle(listName).items.getById(itemId).update(fieldValue) is already return a promise. Your function can be:

var updateListItem = function(itemId, listName, fieldValue) {
  return $pnp.sp.web.lists
    .getByTitle(listName)
    .items.getById(itemId)
    .update(fieldValue);
};

To troubleshoot I would suggest:

  1. Check if the list name provided is correct:
var listName = '[your_list]';
$pnp.sp.web.lists.getByTitle(listName).then(console.log); 
// Should return list metadata, if not, then you're trying wrong name
  1. Check field internal names and that you provide corresponding data type format:
var listName = '[your_list]';
var itemId = [item_id];
$pnp.sp.web.lists.getByTitle(listName).items.getById(itemId ).get().then(console.log); 
// Check the list of possible basic fields 
// `WorkDescription` can be named something else, like `WorkDescription0`

Answer by Alaina Robles

Actually I want to to load data 10-20 on second click but problem is I am not able to load data

– Jon

Mar 12 ’19 at 21:48

,

1

Your initial id is 10, are you trying to get id+1 every time you hit the next button? It seems like your btnClick func is getting the value from Pagination component instead. Don’t think there’s a value at e.target.value.

– Shawn Yap

Mar 12 ’19 at 21:24

,I believe you want to retrieve the id from the state. Which would make your function like so:,Is not going to work. e.target.value is undefined in a button and, when doing undefined + 1, you’ll receive an NaN.

Your btnClick function:

btnClick(e) {
  const id = e.target.value;
  this.setState({
       id: id+1
    },
    () => this.getData()
  )
}

I believe you want to retrieve the id from the state. Which would make your function like so:

btnClick(e) {
  const { id } = this.state;
  this.setState({
       id: id+1
    },
    () => this.getData()
  )
}

Or you might want to derive your setState call from your current state, like so (and I also removed the not needed arrow function declaration):

btnClick(e) {
  this.setState(({ id }) => ({
       id: id+1
    }),
    this.getData
  )
}

Answer by Myra Weiss

axios.post('/formulas/create', {
	name: "",
	parts: ""
})
.then(response => { 
	console.log(response)
})
.catch(error => {
    console.log(error.response)
});

Answer by Paola Estes

I am using axios and trying to post to localhost:3000/posts and getting this error above. Here is the code:,

Sponsor

Sponsor axios/axios

,
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
,I’m closing this PR as it doesn’t seem an issue in Axios but in your web server.

import axios from 'axios';
import {
  GET_ALL_POSTS,
  GET_POST,
  CREATE_POST,
  DELETE_POST,
  UPDATE_POST
} from './types';

const ROOT_URL = 'http://localhost:3000';

export function createPost({content, title}, cb) {
  return function(dispatch) {
    axios.post(`${ROOT_URL}/posts`, {content, title})
      .then((response) => {
        console.log(response);
        dispatch({
          type: CREATE_POST,
          payload: response
        });
      })
      .then(() => cb())
      .catch((error) => {
        if(error.response) {
          console.log(error.response);
        }
        console.log("Problem submitting New Post", error);
      });
  }
}

Answer by Leonidas Wilkerson

It’s a bad request. The server expects some other body/payload or headers. What does the error actually say? No error message other than 400? Check the docs if it’s not your own server you’re hitting.,You are missing a backtick at the URL. Maybe this causes the error?,The server doesn’t like your request, so you should really check the docs for the login api at the server. Can’t really help unless we know what service you’re trying to log in to.,oh, that missed while copy-pasting. That’s not the error…Thanks

data: {
    "Username": "[email protected]",
    "Password": "[email protected]",
    "grant_type": "password"
}

I hardly never saw keys written with a capital letter, plus personally I never use them as strings, I just write:

username: "[email protected]"

Answer by Kaia Osborne

Select the API request that is failing with 500 Internal Server Error in the trace.,In the Trace tool, select the API request that has failed with 500 Internal Server
Error.,500 Internal Server Error — BadPath,500 Internal Server Error — EmptyPath

You may get the following error message:

HTTP/1.1 500 Internal Server Error

In some cases, you may observe another error message which has more details. Here is a sample
error message:

{  
   "fault":{  
      "detail":{  
         "errorcode":"steps.servicecallout.ExecutionFailed"
      },
      "faultstring":"Execution of ServiceCallout callWCSAuthServiceCallout failed. Reason: ResponseCode 400 is treated as error"
   }
}
{ 
"fault":
     { "detail":
           { "errorcode":"steps.servicecallout.ExecutionFailed"
           },"faultstring":"Execution of ServiceCallout service_callout_v3_store_by_lat_lon
 failed. Reason: ResponseCode 404 is treated as error"
          }
     } 
}

<ServiceCallout async="false" continueOnError="true" enabled="true" name="Callout.OamCookieValidation"> 
  <DisplayName>Callout.OamCookieValidation</DisplayName>    
  <Properties />    
  <Request clearPayload="true" variable="serviceCallout.oamCookieValidationRequest">       
    <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>    
  </Request>    
  <Response>serviceCallout.oamCookieValidationResponse</Response>    
  <HTTPTargetConnection>       
    <Properties />       
    <URL>http://{Url}</URL>    
  </HTTPTargetConnection> 
</ServiceCallout>

/opt/apigee/var/log/edge-message-processor/system.log

2017-05-05 07:48:18,653 org:myorg env:prod api:myapi rev:834 messageid:rrt-04984fed9e5ad3551-c-wo-32168-77563  [email protected] ERROR HTTP.CLIENT - HTTPClient$Context.onTimeout() : ClientChannel[C:]@149081 useCount=1 bytesRead=0 bytesWritten=0 age=3002ms lastIO=3002ms .onConnectTimeout connectAddress=mybackend.domain.com/XX.XX.XX.XX:443 resolvedAddress=mybackend.domain.com/XX.XX.XX.XX

telnet

telnet mybackend.domain.com 443 
Trying XX.XX.XX.XX... 
telnet: connect to address XX.XX.XX.XX: Connection timed out

Issue

I’m sending a uid a token and two form inputs from formik to my django rest api for a password reset. When i do so i receive a 400 error with a response that i’m missing the new_password1 and new_password2:

{"new_password1":["This field is required."],"new_password2":["This field is required."]}

I assume this is caused by the fact that i wrapped the values inside the uid and token like this:

axios.post(API.auth.passwordResetConfirm, {uid, token, values} )

If i just do this then it will give me a response asking for the uid and the token but not the passwords:

axios.post(API.auth.passwordResetConfirm, values )

How can i send the two passwords and the uid aswell as the token without the values being «nested» like this (If that is the problem which i think it is)?
Request Payload

This is the entire code:

import { useState } from 'react';
import { useParams } from "react-router"
import axios from "axios"
import { Formik, Field, Form } from 'formik';
import { API } from '../api'

export function ResetConfirm() {
    const [loading, setLoading] = useState(false)
    const [success, setSuccess] = useState(false)
    const { uid } = useParams()
    const { token } = useParams()
    console.log(uid);
    console.log(token);

    function handleSubmit(values, { resetForm }) {
        setLoading(true)
        axios.post(API.auth.passwordResetConfirm, {uid, token, values} )
            .then(res => {
                resetForm()
                setSuccess(true)
            })
            .finally(() => setLoading(false))
    }

    return (
        <div>
            {success && "You will receive a verification email."}
            {loading && "Loading..."}
            <Formik
                initialValues={{
                    new_password1: '',
                    new_password2: '',
                }}
                onSubmit={handleSubmit}>

                {({ errors, touched }) => (
                    <Form>
                        <Field name="new_password1">
                            {({ field, form }) => (
                                <label className="mt-3 block">
                                    <span className="text-gray-700">New password</span>
                                    <input
                                    {...field}
                                    type="text"
                                    className="
                                        mt-1
                                        block
                                        w-full
                                        rounded-md
                                        border-gray-300
                                        shadow-sm
                                        focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50
                                    "
                                    placeholder=""
                                    style={
                                        form.touched.new_password1 && form.errors.new_password1 ? (
                                            { border: '2px solid var(--primary-red)'}
                                        ) : null
                                    }
                                    />
                                </label>
                            )}
                        </Field>
                        <Field name="new_password2">
                            {({ field, form }) => (
                                <label className="mt-3 block">
                                    <span className="text-gray-700">New password</span>
                                    <input
                                    {...field}
                                    type="text"
                                    className="
                                        mt-1
                                        block
                                        w-full
                                        rounded-md
                                        border-gray-300
                                        shadow-sm
                                        focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50
                                    "
                                    placeholder=""
                                    style={
                                        form.touched.new_password2 && form.errors.new_password2 ? (
                                            { border: '2px solid var(--primary-red)'}
                                        ) : null
                                    }
                                    />
                                </label>
                            )}
                        </Field>
                        <button className="mt-3 bg-blue-100 rounded-md shadow-sm text-lg px-5 py-3 hover:bg-blue-200" 
                            type="submit">
                            Submit
                        </button>
                    </Form>
                )}

            </Formik>
        </div>
    )

}

Solution

To un-nest values you can use the spread syntax.

console.log({ uid, token, ...values });
// {
//   uuid: "1",
//   token: "asdf",
//   new_password1: "Password123",
//   new_password2: "Password123",
// }

Note that if values includes the key uid or token, it will override the value of uid/token. So you have to make sure that in only includes whitelisted keys.

Alternatively you could reverse the order. { ...values, uid, token }. This will set the key/values of values first, then set the values of uid and token (overriding the previous value if present).

Answered By – 3limin4t0r

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Your btnClick function:

btnClick(e) {
  const id = e.target.value;
  this.setState({
       id: id+1
    },
    () => this.getData()
  )
}

Is not going to work. e.target.value is undefined in a button and, when doing undefined + 1, you’ll receive an NaN.

I believe you want to retrieve the id from the state. Which would make your function like so:

btnClick(e) {
  const { id } = this.state;
  this.setState({
       id: id+1
    },
    () => this.getData()
  )
}

Or you might want to derive your setState call from your current state, like so (and I also removed the not needed arrow function declaration):

btnClick(e) {
  this.setState(({ id }) => ({
       id: id+1
    }),
    this.getData
  )
}

Finally, you could do a sanity check on your getData function to make sure that this.state.id is actually a number — you could use Number.isNaN().

Related videos on Youtube

React js Tutorial # 20| Handling Unhandled Promise Rejection Api for ecommerce site

04 : 32

React js Tutorial # 20| Handling Unhandled Promise Rejection Api for ecommerce site

How to fix 403 error, when call youtube api . In reactJS project

03 : 02

How to fix 403 error, when call youtube api . In reactJS project

Uncaught (in promise) Error: Request failed with status code 429 || 429 (Too Many Requests) React js

01 : 49

Uncaught (in promise) Error: Request failed with status code 429 || 429 (Too Many Requests) React js

Full React Tutorial #19 - Handling Fetch Errors

07 : 39

Full React Tutorial #19 — Handling Fetch Errors

What is 400 Bad Request | Root cause and Solution of Http 400 code | Common HTTP error code  #6

09 : 39

What is 400 Bad Request | Root cause and Solution of Http 400 code | Common HTTP error code #6

JavaScript Tip: Handling a Failed HTTP Request with fetch

12 : 30

JavaScript Tip: Handling a Failed HTTP Request with fetch

All Things JavaScript, LLC

15  Handling network errors in Axios

05 : 32

15 Handling network errors in Axios

Comments

  • I am using ReactJS, I want to create pagination for my application . When I click on next button I got this error Uncaught (in promise) Error: Request failed with status code 400 . I am fetching page data through API which were built in Loopback. Can someone please help me how to solve this problem because I am new and didn’t much know about ReactJS

    Code

            class Example extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          Item: 5,
          skip: 0
        }
    
        this.handleClick = this.handleClick.bind(this);
      }
    
      urlParams() {
        return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
      }
    
      handleClick() {
        this.setState({skip: this.state.skip + 1})
      }
    
      render() {
        return (
          <div>
            <a href={this.urlParams()}>Example link</a>
            <pre>{this.urlParams()}</pre>
            <button onClick={this.handleClick}>Change link</button>
          </div>
        )
      }
    }
    
    
    ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))
    

    • Your initial id is 10, are you trying to get id+1 every time you hit the next button? It seems like your btnClick func is getting the value from Pagination component instead. Don’t think there’s a value at e.target.value.

    • Actually I want to to load data 10-20 on second click but problem is I am not able to load data

  • Thank You for your comment . I want to show 10 entries on first page when user click on next it will show another 10 entries , first 10 entries will be skipped . It possible through loopback pagination. I did manual it working but I am not able to do it in react

Recents

Got the error «Post 400: Bad request» when I returned status(400). Is that supposed to happen?

Forgive me if this question seems obvious. So I am trying to write a simple React + Node application where I take in certain inputs and store them into the MongoDB database. In my Node app, I returned:

response.status(400).json({error: 'Name or number missing'})

if the request.body is undefined. However, in my inspect console, I keep getting errors such as:

POST http://localhost:3001/api/people 400 (Bad Request)

and

Uncaught (in promise) Error: Request failed with status code 400

Is this to be expected? Or is there something that I’m missing here?

Понравилась статья? Поделить с друзьями:
  • Unc ошибка диска
  • Unb ошибка на стиральной машине leran
  • Unicode error python ошибка
  • Unico live не запускается системная ошибка
  • Unhandled exception произошла одна или несколько ошибок фазмофобия