0

I have a problem. The variable interests is filled up but interestsInput not. What exactly is the problem here? I want to show the interests of a person in a textfield, but it doesnt show the input in the array.

const[firstLoad, setFirstLoad] = useState(true);
const [interestsInput, setInterests] = useState([]);

    const selectedTags = (tags) => {
        setTags(tags)
    };

    useEffect(() => {
        if(firstLoad) {
            getInterests();
            
        }
           
        }, [interestsInput]);
 
    const getInterests = () => {
        axios
        .get("http://localhost:4000/interests",
        { }
        )
        .then((res) => {
            if (res.status === 200) {
                var interests = [];
                for (var i = 0; i < firstInterest.length; i++) {
                    //console.log(myStringArray[i]);
                    //console.log(firstInterest[i]['text'])
                    //console.log(firstInterest[i])
                    interests[i] = firstInterest[i]['text'];
                    setInterests([...interestsInput, interests[i]])
                }
                console.log(interests);
                //setInterests([]);
                //setInterests([...interests]);
                console.log(interestsInput)
            }
        })
        .catch((error) => {
            console.log(error);
        });
    }
Kazim
  • 175
  • 9

2 Answers2

1

Set the new interests outside of the loop, not inside it.

To make things concise, use .map to turn the array of objects into an array of texts.

const getInterests = () => {
    axios
        .get("http://localhost:4000/interests",
            {}
        )
        .then((res) => {
            if (res.status === 200) {
                setInterests([...interestsInput, ...firstInterest.map(int => int.text)]);
            } else {
                throw new Error(res);
            }
        })
        .catch((error) => {
            console.log(error);
        });
};
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank you for your answer. But the `interestsInput` is still empty. – Kazim May 10 '21 at 16:40
  • You won't see the change if you log it inside the same `.then` - log it in the next render. `useState` doesn't update the immutable `const` state immediately. https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately Also consider throwing an error if the status isn't 200 – CertainPerformance May 10 '21 at 16:41
0

Also like user CertainPerformance suggested, you'll need to setState outisde the loop.

// this is redundant, you can achieve this by useEffect with empty array
// const[firstLoad, setFirstLoad] = useState(true);
const [interestsInput, setInterests] = useState([]);

const selectedTags = (tags) => {
  setTags(tags)
};

const getInterests = () => {
  axios
  .get("http://localhost:4000/interests")
  .then((res) => {
    if (res.status === 200) {
      var interests = [];
      for (var i = 0; i < firstInterest.length; i++) {
        interests[i] = firstInterest[i]['text'];
        setInterests([...interestsInput, interests[i]])
      }
    }
  })
  .catch((error) => {
    console.log(error);
  });
}

// Ideally you'd want to put use effects after you have defined your constants & handlers

useEffect(() => {
  // no need of firstLoad condition
  getInterests();
}, []); // this will only run once after first render
Kumar
  • 3,116
  • 2
  • 16
  • 24