Simple redux toolkit
by bilal4 Updated: Dec 7, 2022
Guide Kit
import { applyMiddleware, createStore } from "redux";
import thunk from "redux-thunk";
import axios from "axios";
import { composeWithDevTools } from "redux-devtools-extension";
// action
export const fetchPost = () => {
return async (dispatch, getState) => {
dispatch({ type: "LOAD" });
try {
const respone = await axios.get(
"https://jsonplaceholde.typicode.com/posts"
);
// console.log(respone.data);
dispatch({
type: "FETCH",
payload: respone.data,
});
} catch (error) {
console.log(error.message);
dispatch({ type: "ERR", error });
}
};
};
// reducer
const initState = {
data: [],
load: false,
error: null,
err: false,
};
const postReducer = (state = initState, action) => {
console.log(action.payload);
switch (action.type) {
case "LOAD": {
return {
...state,
load: true,
};
}
case "FETCH": {
return {
...state,
load: false,
data: action.payload,
};
}
case "ERROR": {
return {
...state,
err: true,
error: action.error,
};
}
default: {
return state;
}
}
// if (action.type === "LOAD") {
// return {
// ...state,
// load:true,
// };
// if (action.type === "FETCH") {
// return {
// ...state,
// load:false,
// data:action.payload
// };
// }
// return state;
};
export const store = createStore(
postReducer,
composeWithDevTools(applyMiddleware(thunk))
);