0

trying to set up useContext in my project for flatiron school to have global state for the user and am getting this error "Unhandled Rejection (SyntaxError): Unexpected end of JSON input"

```
import React, { useState, useEffect } from "react";

// create context
const UserContext = React.createContext();


// create a provider component
function UserProvider({ children }) {
  const [user, setUser] = useState({})

  useEffect(() => {
    fetch('/me')
    .then(res => res.json())
    .then(data => {
      setUser(data)
    })
  }, [])

  return (
    <UserContext.Provider value={{user}}>
      {children}
    </UserContext.Provider>
  );
}

export { UserContext, UserProvider };
```
mars916
  • 23
  • 4

1 Answers1

0

You need error handling. res could be null.

useEffect(() => {
  fetch("/me")
    .then((res) => {
      if (res.ok) {
        return res.json();
      } else {
        throw new Error("something went wrong");
      }
    })
    .then((data) => {
      setUser(data);
    })
    .catch((error) => {
      // handling the error you thrown above
      console.error("more info about the error:", error);
    });
}, []);
Confront
  • 488
  • 3
  • 7