Keep checkbox checked after refreshing the page - javascript

I'm trying to fetch all objects from the favorites array and set the checkbox to checked
I've checked online and tried using the localStorage for that yet nothing works and the values aren't saved after refreshing.
Would appreciate any help!
Selected Book Component :
import React, { useEffect, useState } from 'react';
import { bookService } from '../service/book.service';
export const SelectedBook = ({ selectedBook, setFavorites, favorites, removeFavorite }) => {
const onHandleFavorite = (book, e) => {
if (e.currentTarget.checked) {
setFavorites([...favorites, book]);
bookService.addFavorite(book);
} else {
removeFavorite(book);
}
};
const isFavorite = () => {
if (!favorites.includes(selectedBook)) {
return false;
} else {
return true;
}
};
return (
<div className='selected-book-container'>
<input type='checkbox' checked={isFavorite()} onChange={(e) => onHandleFavorite(selectedBook, e)} />
<div className='title'>{selectedBook?.title}</div>
</div>
);
};
Book Page component :
import React, { useEffect, useState } from 'react';
import { bookService } from '../service/book.service.js';
import { BookList } from '../cmps/BookList';
import { SelectedBook } from '../cmps/SelectedBook.jsx';
import { utilService } from '../service/util.service';
export const BookPage = () => {
const [books, setBooks] = useState([]);
const [favorites, setFavorites] = useState([]);
const [index, setIndex] = useState(0);
const [selectedBook, setSelectedBook] = useState();
useEffect(() => {
bookService.favoriteQuery().then((res) => {
setFavorites(res);
});
}, []);
useEffect(() => {
bookService.query().then((res) => {
setBooks(res);
setSelectedBook(res[0]);
});
}, []);
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '37') {
if (index === 0) return;
setIndex(index - 1);
} else if (e.keyCode == '39') {
if (index >= books.length - 1) return;
setIndex(index + 1);
}
}
useEffect(() => {
setSelectedBook(books[index]);
}, [index]);
const removeFavorite = (book) => {
setFavorites(favorites.filter((favorite) => favorite.id !== book.id));
bookService.removeFavorite(selectedBook);
};
return (
<div>
<div className='main-container main-layout'>
<div className='second'>
<SelectedBook
selectedBook={selectedBook}
setFavorites={setFavorites}
favorites={favorites}
removeFavorite={removeFavorite}
/>
<BookList books={favorites} removeFavorite={removeFavorite} />
</div>
</div>
<div className='footer-container'>
<section className='footer'>Footer</section>
</div>
</div>
);
};
Service :
async function favoriteQuery() {
try {
let favorites = await _loadeFavoriteFromStorage();
if (!favorites) return (favorites = []);
return favorites;
} catch (err) {
console.log('cannot load favorites', err);
}
}
function _loadeFavoriteFromStorage() {
return storageService.loadFromStorage(STORAGE_FAVORITE_KEY);
}
Storage Service :
export const storageService = {
loadFromStorage,
saveToStorage
}
function saveToStorage(key, val) {
localStorage.setItem(key, JSON.stringify(val))
}
function loadFromStorage(key) {
var val = localStorage.getItem(key)
return JSON.parse(val)
}
thanks for any kind of help

You're not updating localstorage each time that checked is being changed. You're calling setFavorites with a new set of favorites but this is just changing state. I would suggest creating a function within the book page component which does
function changeFavorite(book, checked){
saveToStorage(book?, checked)
rerender()
}
and having rerender set the state of favorites to whatever is in localstorage to ensure that you have a single source of truth which is found in localstorage and that you change that and not anything else
I'll just add
if (!favorites.includes(selectedBook)) {
return false;
} else {
return true;
}
};
Could really look like
const isFavorite () => favorites.includes(selectedBook)
I also didn't quite understand how you're doing about storing the books in object storage. You should probably have an id of some sorts which you use to save favorite information with

Related

React Uncaught TypeError: Cannot set properties of null (setting 'checked')

I'm using checkbox in react and the theme I'm using provides a hook but when my page loads I get a problem error. I am using checkbox for multiple delete action of elements in the table. I do not have a problem with deletion, but it generates an error on page load due to the check value.
this is the structure i use
https://facit-modern.omtankestudio.com/components/table
the hook i use
import React, { useEffect, useRef } from 'react';
import { useFormik } from 'formik';
import { Checks } from '../components/theme';
const useSelectTable = (data) => {
const selectTable = useFormik({
initialValues: {
selectAll: false,
selectedList: [],
},
});
// Update Select List
useEffect(() => {
if (selectTable.values.selectAll) {
selectTable.setValues({
...selectTable.values,
selectedList: data.map((d) => d?.id?.toString()),
});
} else {
selectTable.setValues({
...selectTable.values,
selectedList: [],
});
}
return () => {};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectTable.values.selectAll]);
// Select All -- indeterminate
const ref = useRef(null);
useEffect(() => {
if (
!!selectTable.values.selectedList.length &&
selectTable.values.selectedList.length !== data.map((d) => d?.id?.toString()).length
) {
ref.current.checked = false;
ref.current.indeterminate = true;
} else if (
selectTable.values.selectedList.length === data.map((d) => d?.id?.toString()).length
) {
ref.current.checked = true;
ref.current.indeterminate = false;
} else if (selectTable.values.selectedList?.length === 0) {
ref.current.checked = false;
ref.current.indeterminate = false;
}
}, [selectTable.values.selectAll, selectTable.values.selectedList, data]);
const SelectAllCheck = (
<Checks
ref={ref}
id='selectAll'
onChange={selectTable.handleChange}
checked={selectTable?.values?.selectAll}
/>
);
const selectItemHandleChange = selectTable.handleChange;
const selectedIdList = selectTable?.values?.selectedList;
return { selectTable, selectItemHandleChange, selectedIdList, SelectAllCheck };
};
export default useSelectTable;
usage:
const { selectTable, SelectAllCheck } = useSelectTable(slotData);
<td>
<Checks
id={slotAreas?.slot_number?.toString()}
name='selectedList'
value={slotAreas?.slot_number?.toString()}
onChange={selectTable?.handleChange}
checked={selectTable?.values?.selectedList.includes(
slotAreas?.slot_number?.toString(),
)}
/>
</td>
error javascript is a common error but I couldn't find a solution in react
can you help to solve this problem

useEffect not firing after updating the component's state

I am making a simple e-commerce website but I've ran into an issue where useEffect() won't fire after making a state change. This code snippet I'll include is for the "shopping cart" of the website and uses localStorage to store all items in the cart. My state will change when quantity changes in the QuantChange() function but will not trigger useEffect(). When I refresh the page after changing an item's quantity, the new quantity won't persist and the old quantity is shown instead. What am I doing wrong? Thanks in advance.
import React, { useState, useEffect } from 'react';
import { SetQuantity } from '../utils/Variables';
import { CartItem } from './CartItem';
const CartView = () => {
const [state, setState] = useState(
JSON.parse(localStorage.getItem('cart-items'))
? JSON.parse(localStorage.getItem('cart-items'))
: []
);
useEffect(() => {
console.log('Updating!');
updateLocalStorage();
});
const updateLocalStorage = () => {
localStorage.setItem('cart-items', JSON.stringify(state));
};
const quantChange = (event) => {
setState((prevState) => {
prevState.forEach((item, index) => {
if (item._id === event.target.id) {
item.quantity = SetQuantity(parseInt(event.target.value), 0);
prevState[index] = item;
}
});
return prevState;
});
};
const removeItem = (id) => {
setState((prevState) => prevState.filter((item) => item._id != id));
};
// Fragments need keys too when they are nested.
return (
<>
{state.length > 0 ? (
state.map((item) => (
<CartItem
key={item._id}
ID={item._id}
name={item.name}
quantity={item.quantity}
changeQuant={quantChange}
delete={removeItem}
/>
))
) : (
<h1 className="text-center">Cart is Empty</h1>
)}
</>
);
};
export default CartView;
import React, { Fragment } from 'react';
import { MAX_QUANTITY, MIN_QUANTITY } from '../utils/Variables';
export const CartItem = (props) => {
return (
<>
<h1>{props.name}</h1>
<input
id={props.ID}
type="number"
max={MAX_QUANTITY}
min={MIN_QUANTITY}
defaultValue={props.quantity}
onChange={props.changeQuant}
/>
<button onClick={() => props.delete(props.ID)} value="Remove">
Remove
</button>
</>
);
};
export const MIN_QUANTITY = 1;
export const MAX_QUANTITY = 99;
// Makes sure the quantity is between MIN and MAX
export function SetQuantity(currQuant, Increment) {
if (Increment >= 0) {
if (currQuant >= MAX_QUANTITY || (currQuant + Increment) > MAX_QUANTITY) {
return MAX_QUANTITY;
} else {
return currQuant + Increment;
}
} else {
if (currQuant <= MIN_QUANTITY || (currQuant + Increment) < MIN_QUANTITY) {
return MIN_QUANTITY;
} else {
return currQuant + Increment;
}
}
}
You are not returning new state, you are forEach'ing over it and mutating the existing state and returning the current state. Map the previous state to the next state, and for the matching item by id create and return a new item object reference.
const quantChange = (event) => {
const { id, value } = event.target;
setState((prevState) => {
return prevState.map((item) => {
if (item._id === id) {
return {
...item,
quantity: SetQuantity(parseInt(value), 0)
};
}
return item;
});
});
};
Then for any useEffect hook callbacks you want triggered by this updated state need to have the state as a dependency.
useEffect(() => {
console.log('Updating!');
updateLocalStorage();
}, [state]);

React converting class into function component issues

I am trying to use React Scheduler with my shifts database. The current state after trying to use hooks instead of class is that I cannot edit any field in the form. I have deleted some of the code to make it cleaner, for now I am trying only to add a shift.
React Scheduler original code:
import * as React from 'react';
import Paper from '#material-ui/core/Paper';
import { ViewState, EditingState } from '#devexpress/dx-react-scheduler';
import {
Scheduler,
Appointments,
AppointmentForm,
AppointmentTooltip,
WeekView,
} from '#devexpress/dx-react-scheduler-material-ui';
import { appointments } from '../../../demo-data/appointments';
export default class Demo extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
data: appointments,
currentDate: '2018-06-27',
addedAppointment: {},
appointmentChanges: {},
editingAppointment: undefined,
};
this.commitChanges = this.commitChanges.bind(this);
this.changeAddedAppointment = this.changeAddedAppointment.bind(this);
this.changeAppointmentChanges = this.changeAppointmentChanges.bind(this);
this.changeEditingAppointment = this.changeEditingAppointment.bind(this);
}
changeAddedAppointment(addedAppointment) {
this.setState({ addedAppointment });
}
changeAppointmentChanges(appointmentChanges) {
this.setState({ appointmentChanges });
}
changeEditingAppointment(editingAppointment) {
this.setState({ editingAppointment });
}
commitChanges({ added, changed, deleted }) {
this.setState((state) => {
let { data } = state;
if (added) {
const startingAddedId = data.length > 0 ? data[data.length - 1].id + 1 : 0;
data = [...data, { id: startingAddedId, ...added }];
}
return { data };
});
}
render() {
const {
currentDate, data, addedAppointment, appointmentChanges, editingAppointment,
} = this.state;
return (
<Paper>
<Scheduler
data={data}
height={660}
>
<ViewState
currentDate={currentDate}
/>
<EditingState
onCommitChanges={this.commitChanges}
addedAppointment={addedAppointment}
onAddedAppointmentChange={this.changeAddedAppointment}
appointmentChanges={appointmentChanges}
onAppointmentChangesChange={this.changeAppointmentChanges}
editingAppointment={editingAppointment}
onEditingAppointmentChange={this.changeEditingAppointment}
/>
<WeekView
startDayHour={9}
endDayHour={17}
/>
<Appointments />
<AppointmentTooltip
showOpenButton
showDeleteButton
/>
<AppointmentForm />
</Scheduler>
</Paper>
);
}
}
My function component code:
import React, { useState } from 'react';
import Paper from '#material-ui/core/Paper';
import { ViewState, EditingState } from '#devexpress/dx-react-scheduler';
import {
Scheduler,
Appointments,
AppointmentForm,
AppointmentTooltip,
WeekView,
ConfirmationDialog,
} from '#devexpress/dx-react-scheduler-material-ui';
const DataSheet = ( { addShift, shifts, deleteShift } ) => {
const [data, setData] = useState(shifts)
const [currentDate, setCurrentDate] = useState('2018-06-27')
const [addedAppointment, setAddedAppointment] = useState({})
const [appointmentChanges, setAppointmentChanges] = useState({})
const [editingAppointment, setEditingAppointment] = useState(undefined)
const changeAddedAppointment = (addedAppointment) => {
setAddedAppointment({ addedAppointment });
}
const changeAppointmentChanges = (appointmentChanges) => {
setAppointmentChanges({ appointmentChanges });
}
const changeEditingAppointment = (editingAppointment) => {
setEditingAppointment({ editingAppointment });
}
const commitChanges = ({ added, changed, deleted }) => {
setData ((????) => {
let { data } = data;
console.log(data); //returns undefined
if (added) {
const startingAddedId = data > 0 ? data[data.length - 1].id + 1 : 0;
data = [...data, { id: startingAddedId, ...added }];
addShift(added);
}
return { data };
});
}
return (
<Paper>
<Scheduler
data={data}
height={660}
>
<ViewState
currentDate={currentDate}
/>
<EditingState
onCommitChanges={commitChanges}
addedAppointment={addedAppointment}
onAddedAppointmentChange={changeAddedAppointment}
appointmentChanges={appointmentChanges}
onAppointmentChangesChange={changeAppointmentChanges}
editingAppointment={editingAppointment}
onEditingAppointmentChange={changeEditingAppointment}
/>
<WeekView
startDayHour={9}
endDayHour={17}
/>
<Appointments />
<AppointmentTooltip
showOpenButton
showDeleteButton
/>
<AppointmentForm />
</Scheduler>
</Paper>
);
}
export default DataSheet
App.js:
import React from 'react';
import backgroundImage from './Resources/BennyBackground.jpeg'
import Header from "./components/Header";
import { useState, useEffect } from "react"
import DataSheet from './components/DataSheet';
const containerStyle= {
width: '100vw',
height: '100vh',
backgroundImage: `url(${backgroundImage})`,
backgroundPosition: 'center',
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
}
const App = () => {
const [shifts, setShifts] = useState([])
useEffect(() => {
const getShifts = async () => {
const shiftsFromServer = await fetchShifts()
setShifts(shiftsFromServer)
}
getShifts()
}, [])
const fetchShifts = async () => {
const res = await fetch(`http://localhost:5000/shifts/`)
const data = await res.json()
return data
}
const addShift = async (shift) => {
const startingAddedId = shifts.length > 0 ? shifts[shifts.length - 1].id + 1 : 0;
shift.id = startingAddedId;
const res = await fetch(`http://localhost:5000/shifts/`,{
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(shift)
})
const data = await res.json()
setShifts([...shifts, data])
}
return (
<div className="container"
style={containerStyle} >
<div className='secondary_container'>
<Header />
<DataSheet shifts={shifts} addShift={addShift}/>
</div>
</div>
);
}
export default App;
I know it is a lot of code and a lot to ask and I would highly appreciate help with this.
I believe the issue is that you are using setXxx as you would use this.setState. In class components, you have one function that modifies all the state (this.setState), while in function components you have a setter function for each field.
So change this:
const changeAddedAppointment = (addedAppointment) => {
setAddedAppointment({ addedAppointment });
}
to this:
const changeAddedAppointment = (addedAppointment) => {
setAddedAppointment(addedAppointment);
}
As far as the commitChanges function goes, you can do the data manipulation before using setData. Also I'm not sure that this let { data } = data would work since there is already a data field. You can try this:
const commitChanges = ({ added, changed, deleted }) => {
let newData = [...data.data];
if (added) {
const startingAddedId = newData > 0 ? newData [data.length - 1].id + 1 : 0;
newData = [...newData , { id: startingAddedId, ...added }];
addShift(added);
}
setData(newData);
};

Why my map fuction dont works in an array?

My map dont appears in my component. I'm trying to make a carousel to show phrases and authors (one testimonial / author at time). I put the map in an array but it doesn't work. I have no idea what the best approach would be. I need a little help.
useQuoteQuery.js: (grabbing the data)
import { useStaticQuery, graphql } from 'gatsby'
export const useQuoteQuery = () => {
const data = useStaticQuery(graphql`
query QuoteQuery {
wpPage(databaseId: { eq: 13 }) {
id
ACF_HomePage {
socialProve {
testimony
author
}
}
}
}
`)
return data
}
on graphql: (it works perfectly)
Quote.js
import React, { useState, useEffect } from 'react'
import { useQuoteQuery } from '../../hooks/useQuoteQuery'
import QuoteImg from '../../images/quote.svg'
import { Content, Wrapper } from './Quote.styles'
import { BiRightArrow, BiLeftArrow } from 'react-icons/bi'
const Quote = () => {
const {
wpPage: { ACF_HomePage: data }
} = useQuoteQuery()
// edited - map return array but returns: Array(3)
// 0: {$$typeof: Symbol(react.element) ......
const quotes = data.socialProve.map(quote => {
return <li key={quote.toString()}>{quote.socialProve}</li>
})
// set interval
useEffect(() => {
const timer = window.setInterval(() => {
setActiveIndex(prev => (prev + 1 >= quotes.length ? 0 : prev + 1))
}, 5000)
return () => {
window.clearInterval(timer)
}
}, [quotes])
const [activeIndex, setActiveIndex] = useState(0)
const activeQuote = quotes[activeIndex]
const handleNextClick = () => {
setActiveIndex(prev => (prev + 1 >= quotes.length ? 0 : prev + 1))
}
const handlePrevClick = () => {
setActiveIndex(prev => prev - 1)
}
return (
<Wrapper>
<Content>
<img src={QuoteImg} alt="aspas" />
<h6>{activeQuote.testimony}</h6>
<p>{activeQuote.author}</p>
<BiLeftArrow
size="20"
className="button-arrow"
onClick={handlePrevClick}
>
Anterior
</BiLeftArrow>
<BiRightArrow
size="20"
className="button-arrow"
onClick={handleNextClick}
>
Próximo
</BiRightArrow>
</Content>
</Wrapper>
)
}
export default Quote
the result:
There is no error in the vs code terminal.
The quotes array is wrapping the array produced by the .map in an extraneous array. Remove the extra array around the result of the .map:
const quotes = data.socialProve.map((quote) => {
return <div key={quote.toString()}>{quote.socialProve}</div>;
});

Save search term on refresh React

I am simply looking to save and restore a search term(form data) when a page is refreshed/reloaded. I have tried several solutions to no avail.
Flow: A user submits a search term and is taken to Spotify to retrieve an accessToken, if it is not already available. The initial page is refreshed once the accessToken is retrieved, but the search must be re-entered. This is not good UX.
I concluded that Web Storage was they way to go, of course it is not the only route. I am not sure if this is something that should be relegated to Lifecycle methods: componentDidMount() & componentDidUpdate(). Perhaps that is overkill? In any event, I attempted to employ both localStorage and sessionStorage. My implementation is obviously off as I am not getting the expected result. React dev tools displays the state of the SearchBar term, but it is not being saved. Also of note is the following: React dev tools shows that the onSubmit event handler is registering as bound () {} instead of the expected bound handleInitialSearchTerm() {}. The console also shows that there are no errors.
No third-party libraries please.
SearchBar.js
import React from 'react';
import "./SearchBar.css";
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
term: this.handleInitialSearchTerm
};
this.search = this.search.bind(this);
this.handleInitialSearchTerm = this.handleInitialSearchTerm.bind(this);
this.setSearchTerm = this.setSearchTerm.bind(this);
this.handleSearchOnEnter = this.handleSearchOnEnter.bind(this);
this.handleTermChange = this.handleTermChange.bind(this);
}
handleInitialSearchTerm = (event) => {
if (typeof (Storage) !== "undefined") {
if (localStorage.term) {
return localStorage.term
} else {
return this.setSearchTerm(String(window.localStorage.getItem("term") || ""));
}
}
};
setSearchTerm = (term) => {
localStorage.setItem("term", term);
this.setState({ term: term });
}
search() {
this.props.onSearch(this.state.term);
}
handleSearchOnEnter(event) {
if (event.keyCode === 13) {
event.preventDefault();
this.search();
}
}
handleTermChange(event) {
this.setState({
term: event.target.value
});
}
render() {
return (
<div className="SearchBar">
<input
placeholder="Enter A Song, Album, or Artist"
onChange={this.handleTermChange}
onKeyDown={this.handleSearchOnEnter}
onSubmit={this.handleInitialSearchTerm}
/>
<button className="SearchButton" onClick={this.search}>
SEARCH
</button>
</div>
);
}
}
export default SearchBar;
Motify.js
let accessToken;
const clientId = "SpotifyCredentialsHere";
const redirectUri = "http://localhost:3000/";
const CORS = "https://cors-anywhere.herokuapp.com/"; // Bypasses CORS restriction
const Motify = {
getAccessToken() {
if (accessToken) {
return accessToken;
}
// if accessToken does not exist check for a match
const windowURL = window.location.href;
const accessTokenMatch = windowURL.match(/access_token=([^&]*)/);
const expiresInMatch = windowURL.match(/expires_in=([^&]*)/);
if (accessTokenMatch && expiresInMatch) {
accessToken = accessTokenMatch[1]; //[0] returns the param and token
const expiresIn = Number(expiresInMatch[1]);
window.setTimeout(() => accessToken = "", expiresIn * 1000);
// This clears the parameters, allowing us to grab a new access token when it expires.
window.history.pushState("Access Token", null, "/");
return accessToken;
} else {
const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`;
window.location = accessUrl;
}
},
search(term) {
const accessToken = Motify.getAccessToken();
const url = `${CORS}https://api.spotify.com/v1/search?type=track&q=${term}`;
return fetch(url, { headers: { Authorization: `Bearer ${accessToken}` }
}).then(response => response.json()
).then(jsonResponse => {
if (!jsonResponse.tracks) {
return [];
}
return jsonResponse.tracks.items.map(track => ({
id: track.id,
name: track.name,
artist: track.artists[0].name,
album: track.album.name,
uri: track.uri,
preview_url: track.preview_url
}));
})
}
...
Please check the code I have added.
Changes I did are below:
1)
this.state = {
term: JSON.parse(localStorage.getItem('term')) || '';
};
setSearchTerm = (term) => {
this.setState({
term: term
},
() => {
localStorage.setItem('term', JSON.stringify(this.state.term)));
}
import React from 'react';
import "./SearchBar.css";
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
term: JSON.parse(localStorage.getItem('term')) || '';
};
this.search = this.search.bind(this);
this.handleInitialSearchTerm = this.handleInitialSearchTerm.bind(this);
this.setSearchTerm = this.setSearchTerm.bind(this);
this.handleSearchOnEnter = this.handleSearchOnEnter.bind(this);
this.handleTermChange = this.handleTermChange.bind(this);
}
handleInitialSearchTerm = (event) => {
if (typeof(Storage) !== "undefined") {
if (localStorage.term) {
return localStorage.term
} else {
return this.setSearchTerm(String(window.localStorage.getItem("term") || ""));
}
}
};
setSearchTerm = (term) => {
this.setState({
term: term
},
() => {
localStorage.setItem('term', JSON.stringify(this.state.term)));
}
search() {
this.props.onSearch(this.state.term);
}
handleSearchOnEnter(event) {
if (event.keyCode === 13) {
event.preventDefault();
this.search();
}
}
handleTermChange(event) {
this.setState({
term: event.target.value
});
}
render() {
return ( <
div className = "SearchBar" >
<
input placeholder = "Enter A Song, Album, or Artist"
onChange = {
this.handleTermChange
}
onKeyDown = {
this.handleSearchOnEnter
}
onSubmit = {
this.handleInitialSearchTerm
}
/> <
button className = "SearchButton"
onClick = {
this.search
} >
SEARCH <
/button> <
/div>
);
}
}
export default SearchBar;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
If it is in hooks i would have done like below:
import React, {
useEffect,
useState,
useRef,
} from 'react';
function App() {
const [value, setValue] = useState(() => {
if (localStorage.getItem('prevCount') === null) {
return 0;
} else {
return localStorage.getItem('prevCount');
}
});
const countRef = useRef();
useEffect(() => {
countRef.current = value;
if (countRef.current) {
localStorage.setItem('prevCount', countRef.current);
} else {
localStorage.setItem('prevCount', 0);
}
});
const handleIncrement = () => {
setValue((value) => +value + 1);
};
const handleDecrement = () => {
if (value === 0) {
return;
} else {
setValue((value) => value - 1);
}
};
return (
<div className="card">
<label className="counterLabel">Simple Counter</label>
<button
className="button"
onClick={handleIncrement}
>
Increment
</button>
<span className="count">{value}</span>
<button
className="button"
onClick={handleDecrement}
>
Decrement
</button>
</div>
);
}
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
So what the above code is doing is that when we inititalize the state value we first check the localStorage , if "term" has value in localStorage we will use that value or else an empty string is initialized.
Using callback of setState inside the method setSearchTerm we set the term value immediately
Try the useLocalStorage hook to save search client side.
// useLocalStorage Hook to persist values client side
function useLocalStorage(key, initialValue) {
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState(() => {
if (typeof window === "undefined") {
return initialValue;
}
try {
// Get from local storage by key
const item = window.localStorage.getItem(key);
// Parse stored json or if none return initialValue
return item ? JSON.parse(item) : initialValue;
} catch (error) {
// If error also return initialValue
console.log(error);
return initialValue;
}
});
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
const setValue = (value) => {
try {
// Allow value to be a function so we have same API as useState
const valueToStore =
value instanceof Function ? value(storedValue) : value;
// Save state
setStoredValue(valueToStore);
// Save to local storage
if (typeof window !== "undefined") {
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
} catch (error) {
// A more advanced implementation would handle the error case
console.log(error);
}
};
return [storedValue, setValue];
}
credit: Brandon Baars

Categories