Unhandled Rejection (SyntaxError): Unexpected end of JSON input error popping up for fetch in UserContext component (useContext react)

28 views Asked by At

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 };
```
1

There are 1 answers

0
Confront On

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);
    });
}, []);