P
P
Pavel2021-05-24 13:17:28
JavaScript
Pavel, 2021-05-24 13:17:28

How to properly organize the work of the component (useEffect and API call)?

Hello, tell me how to correctly build the operation of a component with an API call.
Here is the code itself, and one of the useEffect() options, in this case, I get the old state in the render.

In this variant comes the old state

const [category, setCategory] = useState([]);

    const {id} = useParams();

    useEffect(() => {
        getCategory();
    }, [id]);  
  
    const getCategory = async () => {
        const params = { 
                    id: id 
                };
     
        const data = await API.getOne('category', params); 
        setCategory(data);
    }


If useEffect is following the category state, then of course there is a loop.
This is how looping happens

useEffect(() => {
        getCategory();
    }, [category]);



A variant that seems to work, but the component is rendered twice, which cannot be called a solution :)
rerender

useEffect(() => {
        getCategory();
    }, [id]);  

    useEffect(() => {
            document.title = category.title;
    }, [category.title]);



The solution should obviously be simple :)
But I'm an HTML programmer, so I don't see it here..))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill Makarov, 2021-05-24
@kirbi1996

const {id} = useParams();
const [category, setCategory] = useState([]);


  
    const getCategory = async () => {
        const params = { 
                    id: id 
                };
     
        const data = await API.getOne('category', params); 
        setCategory(data);
    }


    useEffect(() => {
        getCategory();
    }, [id]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question