I tried saving my cart items to local storage but only few of the item gets saved. If i add 2 items, 1 gets saved, if i add 3 items, 2 gets saved, if i add 4, 3 gets saved, and so on.
Here is my code to save them.
const [state, dispatch] = useReducer(StoreReducer, {
cart:
JSON.parse(localStorage.getItem("cart"))
|| [],
});
const addToCart = (product) => {
dispatch({
type: "ADD_TO_CART",
payload: product,
});
localStorage.setItem("cart", JSON.stringify(state.cart));
};
Here is an image describing what is looks like
Here is an image that describes what the application looks like and the local storage:
This function has a major flaw. React doesn't work synchronously.
const addToCart = (product) => {
// this change will be made before next render
dispatch({
type: "ADD_TO_CART",
payload: product,
});
// that's why this `state.cart` is not updated yet
localStorage.setItem("cart", JSON.stringify(state.cart));
};
Try running
localStorage.setItem("cart", JSON.stringify(state.cart));
Inside the reducer
I'd recommend using redux-persist
I'll give a simple example. Please tweak it according to your needs.
We basically have a localstorage.js file to save and read state from local storage.
File: localStorage.js
export const loadState = () => {
try {
const serialState = localStorage.getItem('cart');
if (serialState === null) {
return undefined;
}
return JSON.parse(serialState);
} catch (err) {
return undefined;
}
};
export const saveState = (state) => {
try {
const serialState = JSON.stringify(state);
localStorage.setItem('cart', serialState);
} catch(err) {
console.log(err);
}
};
File: reducer.js
import {
addToCart
} from './actions';
function reducer(state, action) {
if (action.type === addToCart) {
// example
return {
...state,
cart: [...state.cart, action.payload]
}
}
return state;
}
export default reducer;
We read data from localstorage.js by loadState method and put its value in the persistedState constant.
File: store.js
import reducer from './reducer';
import { createStore } from 'redux';
import { loadState } from './localStorage';
const persistedState = loadState();
const initialStore={
/* state of your app */
cart: [],
persistedState
}
export const store=createStore(reducer, persistedState);
In our App.js, we subscribe state changes to store it to web browser's local storage.
File: App.js
import React from "react";
import { Provider } from 'react-redux';
import { store } from './store';
import { saveState } from './localStorage';
store.subscribe(() => {
saveState({
cart:store.getState().cart
});
});
function App() {
return (
<Provider store={store}>
<YourComponent />
</Provider>
);
}
export default App;
That's it. With this approach, there's no need to manually modify your local storage item.
Related
I'm new to React, Redux and have been following tutorials on the topic. I'm come across a lot of issues that I've been able to resolve but I've come across an issue I can't resolve. I set up store, and can even view it through Chrome's Redux Tools and it show correctly, however when I try and dispatch to the Store, I always get a Cannot read property 'dispatch' of undefined error. I have followed numerous tutorials letter for letter, and am still stuck with the same error message.
Index.Js
import Layout from '../components/layout/Layout';
import Home from '../components/Home';
import { getRooms } from '../redux/actions/roomActions';
import { wrapper } from '../redux/store';
export default function Index() {
return (
<Layout>
<Home />
</Layout>
);
}
export const getServerSideProps = wrapper.getServerSideProps(
async ({ req, store }) => {
await store.dispatch(getRooms(req));
}
);
roomConstants.js
export const ALL_ROOMS_SUCCESS = 'ALL_ROOMS_SUCCESS';
export const ALL_ROOMS_FAIL = 'ALL_ROOMS_FAIL';
export const CLEAR_ERRORS = 'CLEAR_ERRORS';
reducer.js
import { combineReducers } from 'redux';
import { allRoomsReducer } from './roomReducers';
const reducer = combineReducers({
allRooms: allRoomsReducer,
});
export default reducer;
Store.js
import { createStore, applyMiddleware } from 'redux';
import { HYDRATE, createWrapper } from 'next-redux-wrapper';
import thunkMiddleware from 'redux-thunk';
import reducers from './reducers/reducers';
const bindMiddleware = (middleware) => {
if (process.env.NODE_ENV !== 'production') {
const { composeWithDevTools } = require('redux-devtools-extension');
return composeWithDevTools(applyMiddleware(...middleware));
}
return applyMiddleware(...middleware);
};
const reducer = (state, action) => {
if (action.type === HYDRATE) {
const nextState = {
...state,
...action.payload,
};
return nextState;
} else {
return reducers(state, action);
}
};
const initStore = () => {
return createStore(reducer, bindMiddleware([thunkMiddleware]));
};
export const wrapper = createWrapper(initStore);
roomReducer.js
import {
ALL_ROOMS_SUCCESS,
ALL_ROOMS_FAIL,
CLEAR_ERRORS,
} from '../constants/roomConstants';
// All rooms reducer
export const allRoomsReducer = (state = { rooms: [] }, action) => {
switch (action.type) {
case ALL_ROOMS_SUCCESS:
return {
roomsCount: action.payload.roomsCount,
resPerPage: action.payload.resPerPage,
filteredRoomsCount: action.payload.filteredRoomsCount,
rooms: action.payload.rooms,
};
case ALL_ROOMS_FAIL:
return {
error: action.payload,
};
case CLEAR_ERRORS:
return {
...state,
error: null,
};
default:
return state;
}
};
roomAcion.js
import axios from 'axios';
import absoluteUrl from 'next-absolute-url';
import {
ALL_ROOMS_SUCCESS,
ALL_ROOMS_FAIL,
CLEAR_ERRORS,
} from '../constants/roomConstants';
//Clear errors
export const clearErrors = () => async (dispatch) => {
return dispatch({
type: CLEAR_ERRORS,
});
};
// Get all rooms
export const getRooms = (req) => async (dispatch) => {
try {
const { origin } = absoluteUrl(req);
const { data } = await axios.get(`${origin}/api/rooms`);
dispatch({
type: ALL_ROOMS_SUCCESS,
payload: data,
});
} catch (error) {
dispatch({
type: ALL_ROOMS_FAIL,
payload: error.response.data.message,
});
}
};
in index.js, your getServerSideProps function should read this;
export const getServerSideProps = wrapper.getServerSideProps((store) => async ({ req }) => {
await store.dispatch(getRooms(req));})
Use the old version of next-redux-wrapper like 6.0.2
I have an app with 2 reducers (city and doctor)
I use sagas.
I have a problem that with weird state overrides.
For example here is the start of fetch doctors action. As you see state was changed for doctor isLoading: false to isLoading: true
After that fetch cities action was started right before. And isLoading for doctors was changed back to false.
On every action dispatch, another reducer state reset.
I have doubt that it's a NextJS specific problem so root store is creating couple of times and cause a race condition.
Technologies: react, redux, react-redux, next-redux-wrapper, next-redux-saga, redux-saga
app.js
....
export default withRedux(createStore)(withReduxSaga(MyApp))
store.js
import { applyMiddleware, createStore } from 'redux'
import createSagaMiddleware from 'redux-saga'
import rootReducer from './rootReducer'
import rootSaga from './rootSaga'
const bindMiddleware = middleware => {
if (process.env.NODE_ENV !== 'production') {
const { composeWithDevTools } = require('redux-devtools-extension')
return composeWithDevTools(applyMiddleware(...middleware))
}
return applyMiddleware(...middleware)
}
function configureStore(initial={}) {
const sagaMiddleware = createSagaMiddleware()
const store = createStore(
rootReducer,
initial,
bindMiddleware([sagaMiddleware])
)
store.sagaTask = sagaMiddleware.run(rootSaga)
return store
}
export default configureStore
rootReducer.js
import { combineReducers } from 'redux'
import { cityReducer } from "./reducers/city"
import { doctorReducer } from "./reducers/doctor"
export default combineReducers({
city: cityReducer,
doctor: doctorReducer
})
city/reducer.js
import {actionTypes} from "../../actions/city"
const initialState = {
cities: []
}
export const cityReducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.FETCH_CITIES:
return initialState
case actionTypes.FETCH_CITIES_SUCCESS:
return {
cities: action.data
}
case actionTypes.FETCH_CITIES_FAILURE:
return initialState
default:
return initialState
}
}
city/actions.js
export const actionTypes = {
FETCH_CITIES: 'FETCH_CITIES',
FETCH_CITIES_SUCCESS: 'FETCH_CITIES_SUCCESS',
FETCH_CITIES_FAILURE: 'FETCH_CITIES_FAILURE',
}
export const fetchCities = () => {
return {
type: actionTypes.FETCH_CITIES
}
}
export const fetchCitiesSuccess = (data) => {
return {
type: actionTypes.FETCH_CITIES_SUCCESS,
data
}
}
export const fetchCitiesFailure = () => {
return {
type: actionTypes.FETCH_CITIES_FAILURE
}
}
city/saga.js
import {call, put, takeLatest} from "redux-saga/effects"
import {actionTypes, fetchCitiesFailure, fetchCitiesSuccess} from "../../actions/city"
import {getCities} from "../../api"
export function* watchFetchCitiesRequest() {
yield takeLatest(actionTypes.FETCH_CITIES, workerFetchCitiesRequest)
}
function* workerFetchCitiesRequest() {
try {
const {data} = yield call(getCities)
yield put(fetchCitiesSuccess(data.results))
} catch (e) {
yield put(fetchCitiesFailure())
}
}
(!) For the doctors reducer/saga/actions the structure is the same except names.
Page.js is the main layout for every page. Basically wraps every page content in _document.js
const Page = ({dispatch}) => {
useEffect(() => {
dispatch(fetchCities())
}, [])
}
const mapStateToProps = ({city}) => ({cities: city.cities})
export default connect(mapStateToProps)(Page)
DoctorList.js Component that /doctor page consumes
import {useEffect} from "react"
import {fetchDoctors} from "../../actions/doctor"
import {getCity} from "../../utils/functions"
import {DoctorItemPreview} from "./DoctorItem"
const DoctorList = ({dispatch, isLoading, isError, response}) => {
useEffect(() => {
getCity() ? dispatch(fetchDoctors()) : null
},[getCity()])
return <>
{!isLoading ? <>
</> : <>
{[...Array(10)].map((e, i) => <span key={i}>
<DoctorItemPreview/>
</span>)}
</>}
</>
}
const mapStateToProps = ({doctor, city}) => ({
isLoading: doctor.isLoading,
isError: doctor.isError,
response: doctor.response,
})
export default connect(mapStateToProps)(DoctorList)
What can be the place where the problem appears? What parts of code do you need for the answer? Thanks
I am pretty sure your reducers will overwrite your current state when returning initialState. See this answer on GitHub.
There are no known race conditions or other problems related to multiple root stores nor reducers in next-redux-saga.
I'm actually working on a small react app, i have an action to check if the current user exist in on the firestore collection 'users' based on the uid, anad then get the user’s profile information.
It works actually this action, but i can't use it in my profile component to display it !
That's the action file:
import 'firebase/firestore'
import firebase from 'firebase/app'
const getUser =()=>{
return (dispatch)=>{
firebase.auth().onAuthStateChanged(firebaseUser => {
if(firebaseUser){
firebase.firestore().collection("users").doc(firebaseUser.uid).get().then( doc => {
const { displayName } = doc.data()
//it works and it shows me on console the name i want
console.log("display name in action: ",displayName)
const currentUser = {
uid: firebaseUser.uid,
displayName
}
dispatch({
type:'GET_USER',
currentUser,
})
})
}
})
}
}
export default getUser ;
when i try to console log it in my profile file, it shows this error "typeError: undefined is not an object (evaluating 'this.props.getUser().currentUser')":
console.log("getting current user: ", this.props.getUser().currentUser )
I expect to display me the displayName but i got that error!
You actually looking for reducer. Action handler is not designed to return data to your component. Action idea is to store data to reducer.
Code below assumes that you have properly connected react-redux with your application.
src/actions/userAction.js
import 'firebase/firestore'
import firebase from 'firebase/app'
export const getUser = () => {
return (dispatch) => {
firebase.auth().onAuthStateChanged(firebaseUser => {
if (firebaseUser) {
firebase.firestore().collection("users").doc(firebaseUser.uid).get().then(doc => {
const {displayName} = doc.data();
const currentUser = {
uid: firebaseUser.uid,
displayName
};
dispatch({
type: 'GET_USER',
payload: currentUser
});
})
}
})
}
};
src/reducers/userReducer.js
const INITIAL_STATE = {
data: {},
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case 'GET_USER':
return {
...state,
data: action.payload
};
default:
return state;
}
};
src/reducers/index.js
import userReducer from "./userReducer";
export default {
user: userReducer
};
src/components/Example.js
import React from 'react';
import connect from "react-redux/es/connect/connect";
import {getUser} from "../actions/userAction";
class Example extends React.Component {
componentDidMount() {
this.props.getUser();
}
render() {
if (!Object.keys(this.props.user.data).length)
return <div>Loading user's data</div>;
return (
<div>
{ JSON.stringify(this.props.user.data) }
</div>
);
}
}
const mapStateToProps = (state) => {
return {
user: state.user
};
};
export default connect(mapStateToProps, {
getUser,
})(Example);
Im running into a problem with my redux to firebase connection i believe.
Trying to grab all jobs from users in firebase.
Have my store setup, action and reducer, not really sure where i am going wrong here so i must be overlooking something, nothing is showing up in console and i put a console.log call on my action and nothing shows still.
my action :
// Grab all Jobs
export const getJobs = (jobs) => ({
type: 'GET_JOBS',
jobs
});
export const startGetJobs = () => {
return(dispatch, getState) => {
const uid = getState().auth.uid;
return database.ref(`users/${uid}/jobs`)
.once('value')
.then((snapshot) => {
const jobs =[];
console.log(jobs);
//Parse the data using snapshot
snapshot.forEach((childSnapshot) => {
jobs.push({
id: childSnapshot.key,
...childSnapshot.val()
});
});
dispatch(getJobs(jobs));
});
};
};
my reducer file :
const jobReducerDefaultState = [];
export default (state= jobReducerDefaultState, action) => {
switch(action.type) {
case 'ADD_JOB':
return [
...state,
action.job
];
case 'REMOVE_JOB':
return state.filter(({ id }) => id !== action.id);
case 'EDIT_JOB':
return state.map((job) => {
if(job.id === action.id) {
return {
...job,
...action.updates
};
} else {
return job;
}
});
case 'GET_JOBS':
return action.jobs;
default:
return state;
}
};
my redux store file :
import { createStore, combineReducers, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk';
import jobsReducer from '../reducers/jobs';
import filtersReducer from '../reducers/filters';
import authReducer from '../reducers/auth';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export default () => {
const store = createStore(
combineReducers({
jobs: jobsReducer,
filters: filtersReducer,
auth: authReducer
}),
composeEnhancers(applyMiddleware(thunk))
);
return store;
};
And trying to call that with this component :
import React from 'react';
import { connect } from 'react-redux';
import JobDataItem from './JobDataItem';
import { startGetJobs } from '../actions/jobs';
class JobData extends React.Component {
ComponentDidMount() {
this.props.startGetJobs();
}
render() {
return (
<div>
{this.props.jobs.map((job) => {
return <JobDataItem key={job.id} company={job.company}/>
})}
</div>
);
};
};
const mapDispatchToProps = (dispatch) => {
return {
startGetJobs: (jobs) => dispatch(startGetJobs(jobs))
}
}
export default connect(undefined, mapDispatchToProps)(JobData);
which passes that data to the jobDataItem component to render to screen below:
import React from 'react';
import { Link } from 'react-router-dom';
const JobDataItem = ({ id, company}) => (
<div>
<Link to={`/edit/${id}`}>
<h3>{company}</h3>
</Link>
</div>
);
export default JobDataItem;
my firebase db formats like:
users/
user-uid/
jobs/
job-uid/
company:"Company Name",
jobTitle:"jobTitle:,
And so on...
Expected output is "Company Name" but nothing shows up at all. i try to just call props.jobs.length and it shows up as 0 as well.
EDITED
1. “Called startGetJobs in componentDidMount(),
2. “Changed props.jobs.map((job)... to this.props.jobs.map((job)...
I now get props is undefined error in console and nothing still appears on screen.
I have been following a guide to setup redux-thunk so I can fetch a users geolocation and then dispatch and update state. However, every time I attempt to dispatch the action with response data, it just sets the data to null.
When I attempt to simulate an API call with a timeout and set some random values, it works without a problem.
geoLocationActions.js
export function geoLocationActions() {
return dispatch => {
const geolocation = navigator.geolocation;
geolocation.getCurrentPosition((position) => {
console.log(position.coords);
dispatch({
type: 'FETCH_USER_LOCATION_SUCCESS',
payload: position
});
});
}
};
MapContainer.js
import React from "react";
import { geoLocationActions } from '../../../actions/geoLocationActions';
import { connect } from 'react-redux';
class MapContainer extends React.Component {
componentWillMount() {
this.props.geoLocationActions();
}
render() {
return (
<div>
<p>Fetching location...</p>
</div>
);
}
}
// update current geolocation state
const mapDispatchToProps = (dispatch) => {
return {
geoLocationActions: () => dispatch(geoLocationActions())
};
}
const mapStateToProps = (state) => {
return {
state: state
};
};
export default connect(mapStateToProps, mapDispatchToProps)(MapContainer);
reducers.js
case 'FETCH_USER_LOCATION_SUCCESS':
return {
...state,
userLocation: action.payload
}
store.js
import { createStore, combineReducers, applyMiddleware, compose } from
'redux';
import reducer from '../reducers/reducers';
import reduxThunk from "redux-thunk";
const rootReducer = combineReducers({
state: reducer
});
export const store = createStore(
rootReducer,
compose(
applyMiddleware(reduxThunk),
window.devToolsExtension ? window.devToolsExtension() : f => f
)
);
It turns an HTML5 Geoposition object. You need to convert it to a regular object that can be serialized with JSON.stringify.
You can use this method:
const geopositionToObject = geoposition => ({
timestamp: geoposition.timestamp,
coords: {
accuracy: geoposition.coords.accuracy,
latitude: geoposition.coords.latitude,
longitude: geoposition.coords.longitude
}
})
Update your geoLocationActions.js like this:
export function geoLocationActions() {
return dispatch => {
const geolocation = navigator.geolocation;
geolocation.getCurrentPosition((position) => {
const positionObj = geopositionToObject(position)
console.log(positionObj);
dispatch({
type: 'FETCH_USER_LOCATION_SUCCESS',
payload: positionObj
});
});
}
};
You can have a look at my repo to see the same code.