I’m having issues where the state of my app updates very slowly. Here’s an image of my main page.
Now when you click on a blue item in the map, it’s associated item should be highlighted red in the list below the map.
This works, but it takes like 1-3 seconds to update. It’s slow.
The store is in the root App component:
function App() {
return (
<div className="App">
<Provider store={store}>
<Header></Header>
<Main />
</Provider>
</div>
);
}
The map and the list of items are in their own component in <Main />
:
<Map></Map>
<MainSub></MainSub>
<Map/>
dispatches an event to the store on a click event called setActive.
function handleMarkerClick(data) {
console.log("click :" + data.name);
dispatch(setActive({ res: data._id.toString() }));
}
<MainSub/>
contains the list and updates according to state change.
const restaurantList = useSelector((state) => {
console.log(state.restaurantSlice);
return state.restaurantSlice;
}, shallowEqual);
This is my slice:
import { createAsyncThunk, createSlice, current } from "@reduxjs/toolkit";
const axios = require("axios");
export const fetchRestaurants = createAsyncThunk(
"fetchRestaurants",
async (teamId) => {
console.log(teamId);
var data = await axios.get("http://localhost:3000/getRestaurant", {
params: {
lon: -72.631119,
lat: 42.206242,
radius: 1,
},
});
return data.data;
}
);
export const restaurantSlice = createSlice({
name: "restaurant",
initialState: {
data: { count: 0, data: [] },
currentActive: 0,
loading: "",
},
reducers: {
setActive: (state, action) => {
var getID = action.payload.res;
state.data.data.map((obj) => {
if (obj._id === getID) {
obj.isActive = true;
}
});
state.data.data.map((obj) => {
if (obj._id === state.currentActive) {
obj.isActive = false;
}
});
state.currentActive = action.payload.res;
},
setRestaurant: (state, action) => {},
getRestaurant: (state, action) => {},
},
extraReducers: (builder) => {
builder.addCase(fetchRestaurants.fulfilled, (state, action) => {
console.log(current(state));
action.payload.data.forEach((x) => {
x.isActive = false;
});
state.data = action.payload;
state.data.data[0].isActive = true;
state.currentActive = state.data.data[0]._id;
state.loading = "loaded";
});
},
});
Also, the extraReducer is what gets the list.
(I don’t know if that’s the root issue)
I understand that createSlice
uses immer behind the scenes so the mutations to the list in setActive shouldn’t be a problem I think. Also if you look in the chrome dev tools, you’ll see that the console.log in useSelector logs twice. I’m not sure why that’s happening since setActive is only dispatched once.
Here’s a link to the code in github. There’s not a lot of code. Only a few components that are self explanatory. https://github.com/CTMatt23/overflow
Thank you for any input. Again this is React Redux Toolkit.