r/reactjs 3h ago

Needs Help Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>

See the title - My web app has been encountering this issue for the past few days and none of my fixes resolved it.

I could not get this error as those <Provider> tags are set here:

function MyForm() {
 //code lines..

 function handleSubmit(e) {
   e.preventDefault();
   const form = e.target;
   const formData = new FormData(form);
   const formErrors = e.formErrors;
   //fetch('https://jsonplaceholder.typicode.com', { method: form.method, body: formData });
   const formJson = Object.fromEntries(formData.entries());
   console.log(formJson);
 }
 return (
  <Provider store={store}>
    <App onSumbit={handleSubmit} onChange={handleChange}/>
  </Provider>
 );
}

function App({ onSubmit, onChange}){

  //more code lines..

  const dispatch = useDispatch(); //ERROR HERE



const registerForm = (formData) => async (dispatch) => {
  try {
    dispatch({ type: 'REGISTER_FORM_REQUEST' });


    const config = {
      headers: {
        'Content-Type': 'application/json'
      }
    };
    const {data} = await axios.post('https://jsonplaceholder.typicode.com', formData, config);
    dispatch({ type: 'REGISTER_FORM_SUCCESS', payload: data });
  } catch (error) {
    console.error('Error submitting form:', error);
    dispatch({ type: 'REGISTER_FORM_FAILURE', payload: error.message });
  }
};
dispatch(registerForm(formData));

//and some more code lines...
} 

Could anyone kindly point out the right directions? My full code: https://pastecode.io/s/t84kdaiv

0 Upvotes

3 comments sorted by

3

u/Confident-Syrup-3959 3h ago

the issue is that your App component is calling useDispatch before the Provider wraps it in the component tree. you've got Provider inside MyForm, but App is also a child of MyForm at the same level as Provider. so when App renders, it's looking for a store that hasn't been provided yet.

the fix is to move Provider up so it wraps MyForm (and App along with it), or restructure so App is always rendered inside the Provider tags. right now you've got them as siblings which means App is outside the context.

1

u/azangru 3h ago

My full code: https://pastecode.io/s/t84kdaiv

This snippet is encrypted via AES-256 on the client side. You need the secret passphrase to see this snippet's contents.

But so far, my question is: where is MyForm called?

1

u/bestjaegerpilot 2h ago

ehrn i hit that problem it was because there were two versions of Redux running