Lately, I have been trying to use Redux but I get no error and no dev tool error and my page are blank.
So I started my code with the basic Redux boilerplate. I created a userslice, a store and then I provided the store as a wrapper for the <app/>
.
Yet after spending hours I can't get to fix the code. Code should just give me back the username inside a div using useselector
hook that initialized but it does not seem to work.
App.js:
import React from 'react';
import { useSelector } from 'react-redux';
import './App.css';
function App() {
const username = useSelector(state => state.username)
return (
<div className="App">
{username}
</div>
);
}
export default App;
userSlice.js
import { createSlice } from "@reduxjs/toolkit";
export const userSlice = createSlice({
name:'user'
,
initialState:{
username:'Tony stark',
post:'',
},
reducers:{
updatePost:(state,action)=>{
state.username = action.payload;
}
}})
export const { updatePost} = userSlice.actions;
export default userSlice.reducers;
store.js
import { configureStore } from '@reduxjs/toolkit';
import userSlice from '../redux/userSlice'
export const store = configureStore({
reducer: {
user: userSlice,
},
});
index.js
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from '../src/redux/store'
import App from './App';
import './index.css';
const container = document.getElementById('root');
const root = createRoot(container);
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
As it's in the userSlice
you'll need to get it from the user
property of the Redux root state, like so:
const username = useSelector(state => state.user.username)
Your initial Redux state (annotated) should look like this:
{ // <-- state
user: { // <-- state.user
username: 'Tony stark', // <-- state.user.username
post: '' // <-- state.user.post
}
}