首页 > 解决方案 > React - API Call to set mutliple state variables (Better Alternatives)

问题描述

I am learning react and during this process I was trying to set multiple state variables inside a single useEffect hook. I just wanted to know, if my approach is the right way to set multiple state variables. Please take a look and advice if there is a better approach.

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

    const App = () => {
        const reqUrl = 'https://hn.algolia.com/api/v1/search?query=redux'
        const initialStateValue = [{ id: 0, value: ' --- Select A State --- ' }];

        const [initialJsonData, setInitialJsonData] = useState({ hits: [] });
        const [tagTypes, setTagTypes] = useState([]);
        const [stateSelected, setStateSelected] = useState(initialStateValue[0].value);


        useEffect(() => {
            axios(reqUrl).then(result => {
                const tagTypeLocal = { ...result.data.hits[0] }
                setTagTypes(tagTypeLocal._tags) --> setting the state variable tagTypes
                console.log(tagTypeLocal._tags)
                setInitialJsonData(result.data) --> setting the state variable initialJsonData
            })

        }, [])

标签: react-hooks

解决方案


Yes, this is an acceptable implementation for updating multiple state items with the useEffect hook.

And to address one of the comments to your question, it is more than fine to use multiple state variables as they might be updated at different times as suggested from the CodeSandbox you linked. In fact this approach is recommended in the React docs.


推荐阅读