0

Below code is a method inside a class based component for react, in my opinion following code should work like this:

  1. first request will add data to both "data" and "one" variables.
  2. second request will add new field to each element inside "data" array.

So now "one" variable should only contains data from first request, but it will show new fields from second request too. what is happening here?

(I checked another tool like "superagent" too, but it has same behavior like axios)

loadData (id = undefined) {
    // here i want to store real data for my app
    let data = []
    //

    // this is a temporary variable which i used only to find out what is happening here
    let one = []
    //

    // first axios request
    axios.get('/loadContainers', {
        headers: {
            id: id
        }
    })
    .then((res) => {
        data = res.data.categories[0].categories
        one = res.data.categories[0].categories

        getData()
    })
    .catch((err) => {
        console.log(err)
    })
    //

    // second axios request
    const getData = () => {
        data.forEach((current, index) => {
            axios.get('/relatedElements', {
                headers: {
                    parentId: current.parentId
                }
            })
            .then((res) => {
                data[index].relatedElements = res.data.count[0].count
            })
            .catch((err) => {
                console.log(err)
            })
        })
    }
    //

    // print "one" variable when all the requests are done
    setTimeout(() => {
        console.log(one)
    }, 8000)
    //
}
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    You've set both `data` and `one` to reference the same object. If you want them to be separate copies, clone the original. – Heretic Monkey Mar 06 '20 at 14:06
  • Thank you, I understood the concept, but i don't know how to solve the problem in action, can you tell me which parts of my code should change? – ADeveloperFromEarth Mar 06 '20 at 14:25
  • Thank you so much, after made following changes everything solved: ```________ data = [...data, ...res.data.categories[0].categories] ________ one = [...one, ...res.data.categories[0].categories] ________ data[index] = {...data[index], ...{numberOfSubCategory: res.data.count[0].count}} ________``` – ADeveloperFromEarth Mar 06 '20 at 15:15

0 Answers0