Home > database >  How to use Context API with useParams
How to use Context API with useParams

Time:12-04

I have an api with details of a farm and I want to show them in different components using an id. Like the data is used in many components and I want to use Context API to display the data in the components.

So here is the code that fetches the data

let navigate = useNavigate();
const [farm, setFarm] = useState('');
const { username } = useParams();
const { farmId } = useParams();
const [isLoading, setIsLoading] = useState(true);
const user = React.useContext(UserContext);

useEffect(() => {

    let isMounted = true;

    axios.get(`/api/farm/${username}/${farmId}`).then(res => {
        if (isMounted) {
            if (res.data.status === 200) {
                setFarm(res.data.farm);
                setIsLoading(false);
                console.warn(res.data.farm)
            }
            else if (res.data.status === 404) {
                navigate('/');
                toast.error(res.data.message, "error");
            }
        }

    });

    return () => {
        isMounted = false
    };
}, []);

The username is okay because I will use the user context to get the user details. Now, how do Use this from a context into the components, because I have tried, and it is not working.

CodePudding user response:

Well you can do it by adding another context for farm.

Your context file:

export const FarmContext = React.createContext();

export function FarmProvider({ children }) {
  const [farm, setFarm] = useState();

  return (
    <FarmContext.Provider value={{farm, setFarm}}>
      { children }
    </FarmContext.Provider>
  )
}

And instead of this:

const [farm, setFarm] = useState();

Use this:

const { farm, setFarm } = useContext(FarmContext);

CodePudding user response:

Include setIsLoading and setFarm into your dependency array. The dispatch function changes during a re-render. In your case, during development double renders components to detect issues with state management.

useEffect(() => {
   ....

}, [ setIsLoading, setFarm]);
  • Related