0

I am calling this api inside a context provider:

const url = 'http://127.0.0.1:8000/api/posts/'

const PostListContextProvider = (props) => {
    const [posts, setPosts] = useState([])

    useEffect(async () => {
        const {data} = await axios.get(url);
        setPosts(data)
    }, [posts]);

    return (
        <PostListContext.Provider value={ posts }>
            { props.children }
        </PostListContext.Provider>
    );
}

Upon consuming the context using useContext, this error occurs:

react-dom.development.js:19710 Uncaught TypeError: destroy is not a function

What am I doing wrong?

ps.even though I am getting the error, I am still successfully fetching the data

1

2 Answers 2

3

useEffect should not be async

Do it like this:

useEffect(() => {
        (async () => {
          const {data} = await axios.get(url);
          setPosts(data)
        })()
}, [posts]);
Sign up to request clarification or add additional context in comments.

1 Comment

The reason why you can't use an async function is because that makes the function return a Promise, and useEffect requires that if you return something it should be a function, which it can use to clean up the effect.
2

useEffect is supposed to return a function if it returns something, since you are defining the callback function to useEffect as a promise, what it essentially returns is a promise which is not what it expects.

In order to use a async function within useEffect you would write it like

useEffect(() => {

   async function myFn() {
        const {data} = await axios.get(url);
        setPosts(data)
   }
   myFn();
}, [posts]);

3 Comments

I am still getting the error. Its actually a warning, and it shows that react still assumes I use the previous method
I didn't get you. What is the warning exactly
my bad. I forgot to save. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.