'Data disappear from array after refresh
I have a component where i add data asynchronously,using a mock post api with mirage js and it sends its state in an async thunkn from redux toolkit.Everythings works good,but the main idea is that the data i send to redux thunk,reducer i should map and use in another component,a skill bar. So,i tried to push data from thunk into an array and export it.It works good,everytime i add a new item,it maps in the component and renders,but when i refresh the page,the component have no data,but i need to mentain the state after refresh.My app is conected to redux persistor,but i see that this doesnt help,do you know what can be the problem and how i should fix it,please?
Above you see what i mean.I enter skill name and skill range,and it should render below as a bar,but it doesnt mentain the state after refresh..
Component that should be rendered with the data:
<div>
<ul className="skills">
{skillArray.map((skill, index) => <li
key={skill.name}
style={{ width: `${skill.level}%`}}
>
<p>{skill.name}<span>{skill.level}</span></p>
</li>
)}
</ul>
</div>
Slice,in the addNewSkill action i push data to the array and i use in the component above:
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'
// export const fetchSkills = createAsyncThunk(
// 'skills/fetchSkills',
// async (_, {rejectWithValue}) => {
// try{
// const response = await fetch('/api/skills',{
// method:'GET',
// })
// // console.log(response)
// if(!response.ok){
// throw new Error ('Server Error!');
// }
// const data = await response.json();
// // console.log(data)
// return data;
// } catch(error){
// return rejectWithValue(error.message);
// }
// }
// );
// export const addNewSkill = createAsyncThunk(
// 'educations/addNewSkill',
// async (text,range,{rejectWithValue,dispatch}) =>{
// try{
// const skill={
// name:text,
// range:range
// };
// const response = await fetch('/api/skills',{
// method:'POST',
// headers:{
// 'Content-name' : 'application/json',
// },
// body:JSON.stringify(skill)
// });
// if(!response.ok){
// throw new Error('Can\'t add skill. Server error')
// }
// const data = await response.json();
// dispatch(addSkill(data))
// }catch(error){
// return rejectWithValue(error.message);
// }
// }
// )
// const setError = (state, action) => {
// state.status = 'rejected';
// state.error = action.payload;
// }
// export const skillSlice = createSlice({
// name: 'skills',
// initialState: {
// name:null,
// range:null,
// status: null,
// error: null,
// },
// reducers: {
// addSkill: (state, action) => {
// state.name = action.payload?.name;
// state.range = action.payload?.range;
// },
// // },
// // extraReducers: {
// // [fetchSkills.pending]: (state, action) => {
// // state.status = 'loading';
// // state.error = null;
// // },
// // [fetchSkills.fulfilled]: (state, action) => {
// // state.status = 'resolved';
// // state.skillList = action.payload;
// // },
// // [fetchSkills.rejected]: setError,
// // },
// }}
// )
// export const { addSkill } = skillSlice.actions;
// // export const { addSkill } = skillSlice.actions
// export const selectSkill = (state) => state?.skills;
// export default skillSlice.reducer;
export const fetchSkills = createAsyncThunk(
'skills/fetchSkills',
async (_, {rejectWithValue}) => {
try{
const response = await fetch('/api/skills',{
method:'GET',
})
// console.log(response)
if(!response.ok){
throw new Error ('Server Error!');
}
const data = await response.json();
// console.log(data)
return data;
} catch(error){
return rejectWithValue(error.message);
}
}
);
const setError = (state, action) => {
state.status = 'rejected';
state.error = action.payload;
}
export const skillArray=[]
export const addNewSkill = createAsyncThunk(
'skills/addNewSkill',
async (skillData,{rejectWithValue,dispatch}) =>{
const {skillName,skillRange} = skillData
try{
const skill = {
name: skillName,
range: skillRange,
};
const response = await fetch('/api/skills',{
method:'POST',
headers:{
'Content-name' : 'application/json',
},
body: JSON.stringify(skill)
});
skillArray.push(skill)
if(!response.ok){
throw new Error('Can\'t add skill. Server error')
}
const data = await response.json();
dispatch(setSkill(data))
}catch(error){
return rejectWithValue(error.message);
}
}
)
export const skillSlice = createSlice({
name: "skills",
initialState: {
skills:[],
status: null,
error: null
},
reducers: {
setSkill: (state, action) => {
// console.log("action", action.payload);
// state.name = action.payload?.name;
// state.range = action.payload?.range;
state.skills.push(action.payload);
// localStorage.setItem(state.name,action.payload.range)
},
},
extraReducers:{
[fetchSkills.pending]:(state,action)=>{
state.status = 'loading';
state.error = null;
},
[fetchSkills.fulfilled]:(state,action)=>{
state.status = 'resolved';
state.name = action.payload;
},
[fetchSkills.rejected]: setError,
}
});
const { setSkill } = skillSlice.actions;
export const selectSkill = (state) => state?.skill;
export default skillSlice.reducer;
Root:
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension'
import { persistStore, persistReducer } from 'redux-persist'
import { toggleButtonReducer } from './reducers/toggleButtonReducer'
import storage from 'redux-persist/lib/storage'
import thunk from 'redux-thunk'
import educationReducer from '../features/education/educationSlice';
import skillReducer from '../features/skills/skillSlice'
const rootReducer = combineReducers({
visibilityState: toggleButtonReducer,
educationState: educationReducer,
skills : skillReducer
})
const persistConfig = {
key: 'root',
storage,
}
const persistedReducer = persistReducer(persistConfig, rootReducer)
export const store = createStore(persistedReducer, composeWithDevTools(applyMiddleware(thunk)))
export const persistor = persistStore(store)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
