0

On form submit I am calling an API and I am getting a response from API. I want to use that response value in other places. When I debug I can see value in response but while assigning it using useState it is always null which is the default value at first.

 const[matterID, setMatterID]= useState(null);
 const[matterName, setMatterName]= useState(null);

const submitHandler= async (e)=>{
    e.preventDefault();
    setPosting(true);

    axios.post(constants.MATTER_SAVE_URI, {matterModel:matterDetail, prefix:matterDetail.Prefix, suffix:matterDetail.Suffix}, {
      headers: {
        'Content-Type': 'application/json'
      }})
    .then((response) => {
      setMatterID(prev =>{
        return{...prev, ...response.data.responseData.matterNumberLTB }
      })
  console.log("matteri",matterID);

      setMatterName(response.data.responseData.name);
   //i also tried using this way.
 axios.post(constants.ADD_MEMBER_TO_GROUP + "/" + matterID, {
        headers: {
          'Content-Type': 'application/json'
        }})
      .then((response) => {
        axios.post(constants.ACCESS_ALL_MEMBER_MATTER + "/" + matterID + "/" + hasAccess, {
          headers: {
            'Content-Type': 'application/json'
          }})
}
Sujan
  • 157
  • 1
  • 8
  • How are you checking it's null afterwards? This looks good `setMatterID(prev =>{` – Vivek Bani Jun 23 '21 at 04:28
  • Have you logged the `response` object? What does it give you? – Devatanu Jun 23 '21 at 04:29
  • when i check on controller and console it is null – Sujan Jun 23 '21 at 04:29
  • i have just edited and put console line in above code – Sujan Jun 23 '21 at 04:31
  • 1
    State changes are asynchronous. You can't `console.log` state right after calling it and see new value. Put the `console.log("matteri",matterID);` in the main body of the function to see its latest value – Jayce444 Jun 23 '21 at 04:31
  • 1
    the `setMatterId` and similar functions from `useState` are async calls so you will not see the update. Can you check your 'response' object? – Devatanu Jun 23 '21 at 04:33
  • my problem is after getting matterid i have to call other api . i just edited it complete code – Sujan Jun 23 '21 at 04:43
  • may be i am not calling other api in correct way, i am new to this react. – Sujan Jun 23 '21 at 04:49
  • @Devatanu can you look at this – Sujan Jun 23 '21 at 04:56
  • 1
    In React, state updates are asynchronous, so you can't console log right after enqueueing an update. `submitHandler` was also declared `async` but you don't run any code asynchronously, i.e. you never `await` any asynchronous code to resolve. The second POST request runs right after the first, essentially concurrently. – Drew Reese Jun 23 '21 at 06:22

0 Answers0