'useEffect and API
i'm trying to make a dictionary using React. First of all, i have
const [word, setWord] = useState();
Then, i have the API
const dictionaryApi = async () => {
try {
const data = await axios.get(
`https://api.dictionaryapi.dev/api/v2/entries/en/${input}`
);
setWord(data.data);
} catch (error) {
console.log(error);
}
};
So i the word now received the data.data from the API. I saw that apparently i have to use useEffect, though i don't know why. If the useEffect's second parameter is an empty array, it will run just 1 time right? I have a button with an input, and what i wanna do is store that data from the API in an empty array. So first of all i created a array
const [change, setChange] = useState([]);
And in the click function, i wrote
setChange([...change, "a"]);
So every time i click it, it will ad an 'a'. And i passed it as the useEffect's second parameter, so when i click, the array will change, with that change useEffect will be executed.
Finally, i have another empty array that will receive word
const [resultlist, setResultlist] = useState([]);
setResultlist([...resultlist, word]);
But the first time i click the button, the change array doesn't change, only the second time i click it changes. I feel like i'm making it overcomplicated. How should i do that?
Solution 1:[1]
useEffect(myFunction, [data])
In this example myFunction will be executed each time my variable data is modified, if you provide an empty array, it will only be executed once. If you to call your function when you click on a button you just have to pass the function to the onClick props of your button
<button onClick={myFunction}>Button</button>
I didn't understand clearly what you want to do but if you want to add your input value to the array you received by your api, you can add it like this in the button function
setWord([...word, inputValue])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LucasStbnr |
