Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why when I'm setting Data with Axios it doesn't work

I’m learning React and I’m facing my first problem. I try to set some Data to use it but I failed.
Here is what I do :

const [randomCharacters, setRandomCharacters] = useState([]);

const randomNumber = (minimum,maximum, numberOfCharactersWanted) => {

        let characters = [];

        for (let i = 1; i <= numberOfCharactersWanted; ++i){
            let randomNumber = (Math.random() * (maximum - minimum + 1) ) << 0;
            if (!characters.includes(randomNumber)){
                characters.push(randomNumber);
            } else {
                randomNumber = (Math.random() * (maximum - minimum + 1) ) << 0;
                characters.push(randomNumber);
            }

        }
        return characters.join();
    }

    useEffect(() =>{
        axios.get('https://rickandmortyapi.com/api/character/'+ randomNumber(0,totalCharacters, 6))
            .then((response) => {
                response.data.map((res) => (
                    setRandomCharacters(res.id)

                ))
                //setRandomCharacters(response.data)
            })
    })

TotalCharacter is equal to 826 and when I fetch, I get the goo url, for example =>
https://rickandmortyapi.com/api/character/23,45,89,567,432,9&#8217; but when I fetch the randomCharacters, I can see state overriding over and over instand of getting an array of value and I don’t understand why, any idea ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

change return characters.join(); to return characters.join('');

in your randomNumber function.

reason why, a blank .join() uses , as the default joining value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading