I try to inject React.createContext Api into Thunk withExtraArgument but don’t understand something

Edit:

Option 1:

I think instead of trying to pass the FirebaseContext down to your thunk, you should instead just pass the Firebase object itself. You can’t use context inside of thunk, so either you will need to pass the context value as an argument to your thunk from the component, or simply provide it when you configure the store.

import Firebase, { FirebaseContext } from './firebase';
import reducer from './redux/reducer';

const firebase = new Firebase();
const store = createStore(
  reducer,
  applyMiddleware(thunk.withExtraArgument(firebase)),
);

ReactDOM.render(
  <FirebaseContext.Provider value={firebase}>
    <Provider store={store}>
      <App />
    </Provider>
  </FirebaseContext.Provider>,

  document.getElementById('root')
);

Also, you still need to correct the order of arguments in your thunk. Redux-thunk will call your function with dispatch, getState, firebase in that order. Even though you aren’t using getState you can’t ignore it. It will still be pass as an argument to your thunk.

function doSomeWork() {
  return (dispatch, getState, firebase) => {
    function work() {
      const userRef = firebase.userDoc(firebase.auth.currentUser.uid);
      dispatch(doSomeWorkStart());
    }
    return work;
  };
}

Option 2:

The alternative option, as mentioned, is to access the context inside of your component, and pass it as an argument to your action creator.

function doSomeWork(firebase) {
  return (dispatch, getState) => {
    function work() {
      const userRef = firebase.userDoc(firebase.auth.currentUser.uid);
      dispatch(doSomeWorkStart());
    }
    return work;
  };
}
function MyComponent(props) {
  const dispatch = useDispatch();
  const firebase = useContext(FirebaseContext);

  useEffect(() => {
    dispatch(doSomwWork(firebase))
  },[])

  return <></>;
}

However, I think the first option is your best bet.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top