0

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))
} , [])

2 Answers 2

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

useEffect(() => {
    axios.get('API-address')
    .then(res => {
        setExpensesData(res.data);
    })
    .catch(e => console.log(e))
} , [])
Sign up to request clarification or add additional context in comments.

Comments

1

Last line will improve your application performance you application It will render method called when your expensesData

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.