monkeys73
monkeys73

Reputation: 171

How to access state from another function inside React useEffect

const ClientContextProvider = React.memo((props) => {
    const [httpState, dispatchHttp] = useReducer(HttpReducer, initialHttpState())
    const [username, setUsername] = useState(null)
    const [givenName, setGivenName] = useState(null)
    const [surname, setSurname] = useState(null)

    useEffect(() => {
        loadClient();
    }, [])

    const loadClient = () => {
        console.log('Loading client info...')
         const errorMsg = "Error, unable to get logged in client information!";
         const callbacks = {
             [Constants.SUCCESS]:   {   status: OK,
                                    callback: (responseData) => {
                                        setUsername(responseData.username)
                                        setGivenName(responseData.givenName)
                                        setSurname(responseData.surname)
                                        loadAllJobs(username);
                                }}
        };
        axiosGetRequest(process.env.REACT_MYSERVICE_API_USER_LOGIN, errorMsg, dispatchHttp, callbacks);
     }

    const loadAllJobs = (username: string) => {
        if (username === null) {
            console.log('loadAllJobs: username is undefined')
        } else {
        const errorMsg = "Error, unable to get job information for logged in client!";
    
// Function carries on, calls api again using username as part of url

}

I am trying to access the username state in my loadAllJobs() function. I originally had loadClient() and loadAllJobs() both in the useEffect. Username was always null in the loadAllJobs function so I tried setting a timer on it so that it ran after 7 seconds, thinking then the state would have time to update. This also didn't work. Now I have tried sticking the loadAllJobs function in the callbacks of my initial function so that it happens when the setStates happen too. This also is not working and username is still null when accessed from my loadAllJobs function. Any help appreciated!

Upvotes: 0

Views: 118

Answers (1)

Gh05d
Gh05d

Reputation: 8962

  const callbacks = {
    [Constants.SUCCESS]: {
      status: OK,
      callback: responseData => {
        setUsername(responseData.username);
        setGivenName(responseData.givenName);
        setSurname(responseData.surname);
        loadAllJobs(username);
      },
    },
  };

This won't work simply because state updates are not synchronous. At this state in the lifecycle of the component, username will still be null. It's value will be updated on the next render, but by then it is too late.

But why do you make it so complicated? Just call loadAllJobs like this and you should be fine: loadAllJobs(responseData.username).

Upvotes: 1

Related Questions