0

I have the following sample code which makes an api call when a form is submitted. How do I wait for 'apiResult' to be set before assigning value1 and value2?

I thought 'awaiting' axios would do this, but React is telling me it can't read the property 'field1' of null, as it's obviously trying to set the two values before either the data has been returned from the api call or before React has set the state (setApiResult).

What's the correct way to do this, please? Ideally, I only want to make one api call per form submission.

const Example = () => {

    const [state, setState] = useState()
    const [apiResult, setApiResult] = useState(null)

    async function handleSubmit() {

        const apiData = await axios(
            `https://someapiurl.com/apiquery=${state}`
        )
        setApiResult(apiData)

        const value1 = apiResult.field1.data;
        const value2 = apiResult.field2.data;

        // ... DO SOMETHING WITH VALUE1, VALUE2
    }

    return (
        <form onSumbit={handleSubmit}>
            <input 
                onChange={(e) => setState(e.target.value)}
                type="text" />
        </form>
    )
}

Any help very much appreciated, Matt.

Ray Purchase
  • 681
  • 1
  • 11
  • 37

2 Answers2

0

You are trying to access state immediately after setting it . Your state wont reflect immediately . You can use apiData instead .

       async function handleSubmit() {

        const apiData = await axios(
            `https://someapiurl.com/apiquery=${state}`
        )
        setApiResult(apiData)

        const value1 = apiResult.field1.data;
        const value2 = apiResult.field2.data;

        // ... DO SOMETHING WITH VALUE1, VALUE2
    }

Also axios wraps your response inside the data object . so you should be doing apiData.data.field1.data

Please refer this - useState set method not reflecting change immediately

Shyam
  • 5,292
  • 1
  • 10
  • 20
0

In react the state updates are asynchronous. So the setApiResult(apiData) won't immediately update the react state.

So if the initial value of ApiResult was null it will still have null value unless the update is complete.

The problem can be solved as below

Since the value apiData is already present in the scope use that variable to set values for value1 and value2

So the handleSubmit function will look like

async function handleSubmit() {

const apiData = await axios(
    `https://someapiurl.com/apiquery=${state}`
)
setApiResult(apiData)

const value1 = apiData.data.field1.data;
const value2 = apiData.data.field2.data;

// ... DO SOMETHING WITH VALUE1, VALUE2

}