I am trying to change the redux state outside a component in an api script I have tried this:
api script:
import store from "./index.jsx";
import foo from "./actions.js";
const state = store.getState();
store.dispatch(foo("Hello world!"));
/*^^^ERROR^^^ Error message: state.dispatch is not a function*/
index.js:
//Importing packages
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App.jsx";
import reportWebVitals from "./reportWebVitals";
import { Provider } from "react-redux";
import { createStore } from "redux";
import reducers from "./redux/reducers/index.js";
//Redux configuration
export const store = createStore(reducers);
//Render app
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
reportWebVitals();
Can anyone please help thanks!
Kind regards Alvin.
UPDATE: I have found another issue in this code: When I run the code there are no errors but when I run this function by pressing a button it gives me this error:
action of type "AUTH_SIGN_IN", the slice reducer for key "login" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.
CodePudding user response:
You can not dispatch
using the state
like this state.dispatch(foo("Hello world!"));
you can dispatch
using the store
.
You can do like this way store.dispatch(foo("Hello world!"));
.
Example :
import React from "react";
import ReactDOM from "react-dom";
import * as ReactRedux from "react-redux";
import * as Redux from "redux";
function onIncriment() {
return {
type: "INCRIMENT"
};
}
const initialState = {
counter: 0
};
function counterReducer(state = initialState, action) {
switch (action.type) {
case "INCRIMENT": {
return {
...state,
counter: state.counter 1
};
}
default:
return state;
}
}
const staticReducer = {
counter: counterReducer
};
let store = Redux.createStore(Redux.combineReducers({ ...staticReducer }));
function App() {
return <div>Counter value : {store.getState().counter.counter} </div>;
}
ReactDOM.render(
<ReactRedux.Provider store={store}>
<App />
</ReactRedux.Provider>,
document.getElementById("root")
);
store.dispatch(onIncriment())
CodePudding user response:
You must create the store on a separate file (I usually have src/store.ts). You will be able to import your store on index.js (for the React provider) and you'll be able to import it outside React too and simply store.dispatch(...)
.