I have been trying to use my redux knowledge to build small projects in order to train myself more on the topic. lately, I have been trying to use redux but I get no error and no dev tool error and my page are blank. I will post bellow my code so it's more clear. so I started my code with the basic redux boilerplate that I memorized. I created a userslice and a store and then I provided the store as a wrapper for the yet after spending hours I can't get to fix the code the code should just give me back the username inside a div using useselector hook that I 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))
CodePudding user response:
If it's in the userSlice you'll need to get it like from the user
property of the root state, like so:
const username = useSelector(state => state.user.username)
Your initial Redux state should look like this:
{ // <-- state
user: { // <-- state.user
username: 'Tony stark', // <-- state.user.username
post: '' // <-- state.user.post
}
}