Home > Software design >  Setting multiple states in custom hook
Setting multiple states in custom hook

Time:10-18

I'm tyring to make a React custom hook where it recieves a url as a parameter to retrieve data using axios. I can retrieve the data I need with this:

import axios from 'axios';
import { useEffect, useState } from 'react';

//Takes a url parameter
const useList = (url) => {

    const [data, setData] = useState( [] );
    
    //Gets data from url parameter passed in and sets the data in State.
    useEffect(() => {
        axios.get(url).then(data => {
            setData(data.data.content);
            console.log(data);
            
        })
    }, [url]);

    return {data};
}

export default useList;

I'd like to add another state:

const [pageNumber, setPageNumber] = useState(0);

and then have that state updated within the same useEffect hook, since the response I retrieve from the URL has pagination data showing totalPages.

I added it to the useEffect hook like so:

useEffect(() => {
        axios.get(url).then(data => {
            setData(data.data.content);
            setPageNumber(pageNumber.data.totalPages);
        })
    }, [url]);

And get the error: enter image description here

How can I update multiple states within one useEffect hook? (Pretty new to React)

CodePudding user response:

pageNumber is initialized with a number so you cant do pageNumber.data, you should do the following:

useEffect(() => {
        axios.get(url).then(data => {
            setData(data.data.content);
            setPageNumber(data.totalPages);
        })
    }, [url]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Depending on the api design its setPageNumber(data.totalPages) or setPageNumber(data.data.totalPages)

  • Related