0

I'm trying to update my state values and then use it for axios to send user details to my api, but first time user clicks on register form submit button to send his information , useState seems not work, second time my state has value , this is my code:

import React, { createContext , useState, useEffect } from 'react';

export const RegContext = createContext();

const RegContextProvider = (props) => {

    const [UserDetail, setUserDetail] = useState({});

    const addUser = (first_name, last_name, phone_number) => {
        setUserDetail(UserDetail => ({...UserDetail, first_name, last_name, phone_number}));
        console.log(UserDetail);
        //after set state i need to send details to axios
        //axios.post('https://api.espadev.ir/api/v1/auth/auth/register' , {UserDetail}) 
        //first time server returns 400 error because state is empty and i should click again on my button to change state.
    }

    return (
        <RegContext.Provider value={{UserDetail, addUser}}>
            { props.children }
        </RegContext.Provider>
    );
}

export default RegContextProvider;

enter image description here

Can you help me to solve this problem?

Rmanx77
  • 221
  • 3
  • 11
  • 1
    State updates are async. The updated value will not be available for use immediately. You will need to move you logic to a `useEffect`. – Brian Thompson Mar 26 '20 at 19:16
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Brian Thompson Mar 26 '20 at 19:18

1 Answers1

1

To resolve you issue you should pass all data into the addUser

For example

const addUser = (newUserDetail ) => {
        setUserDetail(newUserDetail ));
        console.log(newUserDetail );
}

You can see new state only in useEffect or combine new data with UserDetail

const addUser = (first_name, last_name, phone_number) => {
  const newUserDetails = {...UserDetail, first_name, last_name, phone_number};

But in this case you can use old UserDetail if you call addUser more then react can update you component