Home > Enterprise >  React context api dispatch does not dispatch values when called when called
React context api dispatch does not dispatch values when called when called

Time:07-30

I am creating an app with reactjs and I am using context api as my state management tool

but the dispatch does not dispatch the values

city shows undefined even after the dispatch has been called.

SearchContext

Here I created the initial state where the city is undefined, date is an empty array and option values are undefined on the initial state

I just have two actions search and reset action which should be dispatched when the user click on a button

import { useReducer } from "react"
import { createContext } from "react"

const INITIAL_STATE = {
    city: undefined,
    dates: [],
    options: {
        adult: undefined,
        children: undefined,
        room: undefined,
    }
}

export const SearchContext = createContext(INITIAL_STATE)

const SearchReducer = (state, action) => {
    switch (action) {
        case "NEW_SEARCH":
            return action.payload;
        case "RESET_SEARCH":
            return INITIAL_STATE;
        default:
            return state
    }
}

export const SearchContextProvider = ({ children }) => {
    const [state, dispatch] = useReducer(SearchReducer, INITIAL_STATE)

    return (
        <SearchContext.Provider
            value={{ city: state.city, dates: state.dates, options: state.options, dispatch }}>
            {children}
        </SearchContext.Provider>
    )
}

index.js

I wrapped the whole app with my searchcontext provider so that I can access the values that is passed down to all the components

import App from './App';
import { SearchContextProvider } from './context/SearchContext';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <SearchContextProvider>
    <App />
    </SearchContextProvider>
  </React.StrictMode>
);

header.js

import { useContext } from "react";
import { SearchContext } from "../../context/SearchContext";

const Header = () => {
  const { dispatch } = useContext(SearchContext)

const handleSearch = (e, dispatch) => {
    dispatch({ type: "NEW_SEARCH", payload: { destination, "dates": "14-may-2122", options } })
    navigate("/hotels", { state: { destination, dates, options } });
  };

  return (
    <div className="header">
       <button className="headerBtn" onClick={(e) => handleSearch(e, dispatch)}>
          Search
       </button>
    </div>
  )

}

CodePudding user response:

You forgot .type

const SearchReducer = (state, action) => {
    switch (action.type) { // <--- add `.type` here
        case "NEW_SEARCH":
            return action.payload;
        case "RESET_SEARCH":
            return INITIAL_STATE;
        default:
            return state
    }
}
  • Related