Search code examples
reactjsarraylistsetstate

How to Store All Axios Response Data in State Using the Map Method in React.js


I need to store all the information from an Axios response in the state as JSON and use the map method to process the data.

The problem is that when I use the map method after the Axios request, it only adds the last JSON object to the state, even though there are 9 objects in my JSON.

How can I ensure all objects from the JSON response are stored in the state?

Here is my code:

const [expensesData , setExpensesData] = useState([])

useEffect(() => {
    axios.get('API-address')
    .then(res => {
        res.data.map( info => {
            setExpensesData(
                [
                    ...expensesData,
                    {info}
                ]
            )
        })
    })
    .catch(e => console.log(e))
} , [])

Solution

  • const [expensesData , setExpensesData] = useState([])
    
    useEffect(() => {
        axios.get('API-address')
        .then(res => {
            setExpensesData(res.data);
        })
        .catch(e => console.log(e))
    } , [])