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

iscream
  • 680
  • 2
  • 8
  • 20
  • 1
    Does this answer your question? [Getting error after i put Async function in useEffect](https://stackoverflow.com/questions/58495238/getting-error-after-i-put-async-function-in-useeffect) – wentjun Jun 05 '20 at 15:39

2 Answers2

3

useEffect should not be async

Do it like this:

useEffect(() => {
        (async () => {
          const {data} = await axios.get(url);
          setPosts(data)
        })()
}, [posts]);
Łukasz Karczewski
  • 1,084
  • 8
  • 12
  • 3
    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. – Jacob Jun 05 '20 at 15:38
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]);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400