Skip to content

Instantly share code, notes, and snippets.

@dillon
Last active December 18, 2019 23:14
Show Gist options
  • Save dillon/6888de68954ac40c639ce8eed08b4fd3 to your computer and use it in GitHub Desktop.
Save dillon/6888de68954ac40c639ce8eed08b4fd3 to your computer and use it in GitHub Desktop.
Persist React Context to local state
import React from 'react';
const initialState = {
location: null,
doctor: null,
dateTime: null,
firstName: null,
lastName: null,
email: null,
phone: null,
petName: null,
confirmed: null,
success: null,
setLocation: () => {},
setDoctor: () => {},
setDateTime: () => {},
setClientInfo: () => {},
confirmAppointment: () => {},
persistState: () => {},
};
export const BookingContext = React.createContext(initialState);
class BookingState extends React.Component {
constructor(props) {
super(props);
this.state = initialState;
}
componentDidMount() {
Object.keys(this.state).forEach((key) => {
const value = JSON.parse(localStorage.getItem(key));
if (value) this.setState({ [key]: value });
});
}
setValue = ({ name, value }) => {
if (name && value) {
this.setState({ [name]: value });
this.persistState({ name, value });
return true;
}
return false;
}
confirmAppointment = async () => {
const {
location,
doctor,
dateTime,
firstName,
lastName,
email,
phone,
petName,
} = this.state;
if (!(location && doctor && dateTime && firstName && lastName && email && phone && petName)) {
return false;
}
this.setState({ success: true });
return true;
}
persistState = async ({ name, value }) => {
localStorage.setItem(name, JSON.stringify(value));
}
render() {
const { children } = this.props;
return (
<BookingContext.Provider
value={{
...this.state,
setValue: this.setValue,
}}
>
{children}
</BookingContext.Provider>
);
}
}
export default BookingState;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment