How can I save this page to localStorage - javascript

When I deploy my application.
Each time I refresh the brown. I get a message saying page not found.
I know that React JS is a memory based applicaion, it does not store anything.
If I need to, I will have to use localStorage and many other options out there like IndexedDB, cookies etc.
My problem is, what I need to store to localStorage in not a function or method. My page has only content.
How do I add that to localStorage or what do I do ?
import React, { useState, useEffect } from "react";
import {Link, generatePath } from "react-router-dom";
import Navigationbar from "../components/navigationbar/navigationbar";
import ProductsHeader from "../components/products-header/ProductsHeader";
import Shopbybrand from "../components/shopbybrand/shopbybrand";
import Footer from "../components/footer/footer";
const Products = ({ products, countCartItem }) => {
return (
<>
<div style={{ background: "transparent", display: "flow-root" }}>
<div
className="productDetails"
style={{
display: "block",
background: "black",
borderRadius: " 0 0 30px 30px",
padding: 20,
marginBottom: 30,
}}
>
<Navigationbar countCartItem={countCartItem} />
<ProductsHeader />
</div>
<div className="container">
<div>
<span style={{ fontSize: 12, fontWeight: 700 }}>Vouchers</span>
<br />
<span style={{ fontSize: 40, fontWeight: 700, }}>Discover</span>
<ul
style={{
listStyle: "none",
padding: 0,
paddingTop: 50,
maxWidth: 1800,
margin: "0 auto",
display: "flex",
flexWrap: "wrap",
justifyContent: "start"
}}
>
{products.map((item) => (
<li
key={item.ProductCode}
style={{ paddingBottom: 15, maxWidth: 240, float: "", display: "flex", margin: "9px" }}
>
<Link
to={generatePath(
"/itemDetail/:ProductCode/:FaceValue/:Vendor/",
{
ProductCode: item.ProductCode,
FaceValue: item.FaceValue,
// Vendor: item.Vendor.replaceAll(/\W/g, "")
Vendor: item.Vendor,
Vat: item.Vat,
}
)}
>
<div
className="card"
style={{ margin: 0, borderRadius: 25, backgroundColor: "#white" }}
>
<img
src={item.Logo}
className="card-img-top"
alt="..."
style={{ width: "390px !important", borderRadius: 25 }}
/>
<div style={{ marginTop: "10px", margin: 20 }}>
<p style={{color: "black"}}>{item.Vendor}</p>
<h6 style={{ fontSize: 19, fontWeight: 600, color: "black" }}>
{item.Description}
</h6>
<h2 style={{ fontSize: 26, fontWeight: 700, color: "black" }}>
R {item.FaceValue}{" "}
<span style={{ display: "none", color: "black" }}>{item.Vat} </span>
</h2>
</div>
</div>
</Link>
</li>
))}
</ul>
</div>
</div>
</div>
<div style={{ display: "flex !important", background: "white", marginTop: 65 }}>
<Shopbybrand />
<Footer />
</div>
</>
);
};
export default Products;

Actually, when you deploy your react app to Netlify it shows error so, to resolve it Add a new file name _redirects inside your build folder & paste the below content-
/* /index.html 200
Now push your new changes to server.

Related

react did not render all rows and just rendered one object and reapeated

it should populate all rows to the table (the rows are from from the api is an array of objects) currently the issue is only render that last object of the array and I have no idea why it keeps on repeating , as you can see on the screenshot it only loads 1 object and then repeats that is why all the rows have the same value.
By the way the rows or the data from the api is an array of objects /
Maybe someone has an idea on how we can address this issue. Thanks.
#rows from the api result from the console log this is the rows that is been feed to the grid
#react code
export const StyledDataGrid = styled(DataGrid)`
.MuiDataGrid-row: nth-of-type(odd) {
background: #E3E0E0
}
.MuiDataGrid-cell {
border-right: 1px solid #C4C4C4;
}
.MuiDataGrid-columnHeader {
border-right: 1px solid #C4C4C4;
}
.MuiDataGrid-columnSeparator--sideRight {
display: none
}
.MuiDataGrid-columnHeaderTitleContainer {
justify-content: space-between;
}
.MuiDataGrid-iconButtonContainer {
visibility: visible;
width: auto;
}
`;
const PortfolioPage: FC = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const { isPending, isError, isSuccess, grid, isSaveSuccess } = useAppSelector(
(state) => state.region
);
const [snackbarOpen, setSnackbarOpen] = useState<boolean>(false);
const [selectedRow, setSelectedRow] = useState<IRegional | null>(null)
const rows = grid ? grid.items : [];
console.log('rows' , rows)
const fetchGridItems = () => {
const payload: IPageListApiRequestPayload = {
accountId: 1,
sortKey: JSON.stringify([]),
sortOrder: JSON.stringify([]),
page: 1,
pageSize: 100,
searchString: '',
};
dispatch(getRegionGrid(payload));
}
useEffect(() => {
// Save success
if (isSaveSuccess) {
setSnackbarOpen(true);
fetchGridItems();
}
}, [isSaveSuccess])
useEffect(() => {
if (router.isReady) {
fetchGridItems();
}
}, [router.isReady]);
const renderList = (data: IEmail) => (
<div style={{display: 'block'}}>
<div>Full Name: {data.firstName} {data.lastName}</div>
<div>Email Address: {data.emailAddress}</div>
</div>
)
const columns: GridColDef[] = [
{
field: "associateDirectorofConstructionOps",
headerName: "Associate Director of Construction Ops",
minWidth: 300,
flex: 0.16,
disableColumnMenu: true,
renderCell: (params: GridRenderCellParams<string>) => (
<>
{
params.row.associateDirectorofConstructionOps ? params.row.associateDirectorofConstructionOps.map((prop: IEmail) => renderList(prop))
: null
}
</>
),
},
];
const fixedColumnLeft: GridColDef[] = [
{
field: "regionName",
headerName: "Region Division",
flex: 0.08,
minWidth: 100,
disableColumnMenu: true,
},
{
field: "subRegionName",
headerName: "Sub-Region",
flex: 0.15,
minWidth: 50,
disableColumnMenu: true,
},
{
field: "marketName",
headerName: "Market",
flex: 0.08,
minWidth: 50,
disableColumnMenu: true,
},
];
const fixedColumnRight: GridColDef[] = [
{
field: "action",
disableColumnMenu: true,
sortable: false,
renderHeader: () => <></>,
renderCell: (params: GridRenderCellParams<string>) => (
<div
style={{
color: "rgb(110 110 110)",
display: "flex",
justifyContent: "space-between",
}}
>
<EditIcon onClick={() => handleClickOpen(params)} />
</div>
),
},
];
const [open, setOpen] = React.useState<boolean>(false);
const handleClickOpen = (data: any) => {
setSelectedRow(data.row);
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<Box sx={{ height: "100vh", background: "#EEEAEA" }}>
<Snackbar
open={snackbarOpen}
autoHideDuration={3000}
onClose={() => setSnackbarOpen(false)}>
<Alert onClose={() => setSnackbarOpen(false)} severity="success" sx={{ width: '100%' }}>
Successfully saved!
</Alert>
</Snackbar>
<EditProperties open={open} handleClose={handleClose} selectedRow={selectedRow} />
<DashboardWrapper seoProps={{
title: "PIM | Regions",
}}
title="Properties"
mainClass="properties-page">
{isError ? <div>Error Loading Regions!</div> : ""}
{isPending ? <>Loading Regions...</> : ""}
{isSuccess ? (
<>
<div
style={{
display: "flex",
justifyContent: "space-between",
width: "636px",
height: "56px",
background: "rgba(37, 36, 41, 0.9)",
padding: "8px 16px 8px 8px",
borderBottomRightRadius: "30px",
}}
>
<Input
size="small"
style={{
width: "461px",
height: "40px",
background: "#FFFFFF",
borderRadius: "4px",
outline: "none",
}}
placeholder="Search by typing property name or address"
startAdornment={
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
}
/>
<Button
variant="contained"
style={{ textTransform: "capitalize" }}
>
Search
</Button>
<div
style={{
display: "flex",
color: "#FFFFFF",
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center",
marginRight: "10px",
}}
>
<TuneIcon style={{ fontSize: "32px" }} />
<span style={{ fontSize: "10px", marginTop: "-5px" }}>
Filters
</span>
</div>
</div>
<TableContainer component={Paper} style={{ marginTop: "24px" }}>
<div
style={{
borderBottom: "1px solid #C4C4C4",
padding: "16px",
display: "flex",
justifyContent: "space-between",
background: "#FFFFFF",
height: "72px",
}}
>
<label
style={{
fontWeight: "600",
fontSize: "24px",
color: "#252429",
alignSelf: "center",
}}
>
{" "}
Regions{" "}
</label>
<div
style={{
alignSelf: "center",
color: "#C4C4C4",
display: "flex",
fontSize: "16px",
}}
>
<IosShareIcon style={{ marginRight: "14px" }} />
Export
</div>
</div>
{/* Table container */}
<div style={{position: "relative", display: 'flex', justifyContent: 'space-between'}}>
{/* Left table */}
<Box
sx={{ boxShadow: 5 }}
style={{
width: "20%",
zIndex: 99,
overflow: "hidden",
background: "#FFFFFF",
}}
>
<StyledDataGrid
autoHeight
getRowId={(row) => row.accountId}
hideFooterPagination={true}
components={{
ColumnSortedAscendingIcon: UnfoldMoreIcon,
ColumnSortedDescendingIcon: UnfoldMoreIcon,
}}
rows={rows}
columns={fixedColumnLeft}
disableSelectionOnClick
experimentalFeatures={{ newEditingApi: true }}
/>
</Box>
{/* Center table */}
<div style={{overflow: 'hidden', width: '70%'}}>
<div style={{ width: '2000px', margin: 'auto', overflow: "hidden"}} >
<StyledDataGrid
autoHeight
getRowId={(row) => row.accountId}
components={{
ColumnSortedAscendingIcon: UnfoldMoreIcon,
ColumnSortedDescendingIcon: UnfoldMoreIcon,
}}
rows={rows}
columns={columns}
pageSize={100}
rowsPerPageOptions={[10, 20, 50, 100]}
disableSelectionOnClick
experimentalFeatures={{ newEditingApi: true }}
/>
</div>
</div>
{/* Right table */}
<Box
sx={{ boxShadow: 5 }}
style={{
width: "10%",
zIndex: 99,
overflow: "hidden",
background: "#FFFFFF",
}}
>
<StyledDataGrid
autoHeight
getRowId={(row) => row.accountId}
hideFooterPagination={true}
components={{
ColumnSortedAscendingIcon: UnfoldMoreIcon,
ColumnSortedDescendingIcon: UnfoldMoreIcon,
}}
rows={rows}
columns={fixedColumnRight}
disableSelectionOnClick
experimentalFeatures={{ newEditingApi: true }}
/>
</Box>
</div>
</TableContainer>
{/* <ActionButtonContainer
btnNameOne="Property"
btnNameTwo="Properties"
btnIconOne={<UploadFileIcon />}
btnIconTwo={<AddIcon />}
/> */}
</>
) : (
""
)}
</DashboardWrapper>
</Box>
Yes because of this
This line is the cause of all these problems
The DataGrid expects a unique key for every row in the table
so it's asking you where it can find that unique key
You're telling it that it can find it inside the accountId prop.
Which is not accurate because it has duplicates
Normally this should be id, but it's null everywhere in your case.
If the data source coming from your API has a property called "id", the MUI DataGrid is automatically going to use it if you didn't set the getRowId prop.

React native - 3 components on the same row instead of vertically stacked

I'm practicing with React Native: in this list every entry returned for my database is composed by 3 items:
Now I want my screen to look like this:
My code is:
<ListItem bottomDivider>
<ListItem.Content style={{textAlign:'left'}}>
<ListItem.Title>{item.title}</ListItem.Title>
<ListItem.Subtitle
style={{color: '#9D7463'}}>
<Image
style={{ alignSelf: "center", borderRadius: 50 }}
source={{ uri: item.probability, width: 48, height: 48 }}
/>
</ListItem.Subtitle>
<ListItem.Subtitle
style={{color: '#000', textTransform: 'uppercase'}}>
{item.country_id}
</ListItem.Subtitle>
<Button
buttonStyle={{backgroundColor: primaryColor, padding: 9, textAlign: "right"}}
title="Follow"
onPress={() => alert(item.id_user)}
/>
</ListItem.Content>
</ListItem>
You need to change the flexDirection to row. Notice that this is different from the web:
Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with flexDirection defaulting to column instead of row
Thus, changing the flexDirection to row of the parent view, and setting flex:1 for each child, should solve the issue.
<ListItem.Content style={{flexDirection: "row"}}>
<ListItem.Subtitle
style={{color: '#9D7463', flex: 1}}>
<Image
style={{ alignSelf: "center", borderRadius: 50 }}
source={{ uri: item.probability, width: 48, height: 48 }}
/>
</ListItem.Subtitle>
<ListItem.Subtitle
style={{color: '#000', textTransform: 'uppercase', flex: 1}}>
{item.country_id}
</ListItem.Subtitle>
<Button
buttonStyle={{backgroundColor: primaryColor, padding: 9, textAlign: "right", flex: 1}}
title="Follow"
onPress={() => alert(item.id_user)}
/>
</ListItem.Content>
In this component you can use flexbox
<ListItem.Content style={{width: '100%', display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center'}}>

Uncaught TypeError: Cannot read properties of undefined (reading 'companyName') JS Objects

i have a problem about when i trying mapping my data. I want a reach company name in supplier in products. How can i fix it?
{products.map((repo) => (
<div
style={{
backgroundColor: "#c1d3d4",
marginTop: 50,
display: "flex",
flexDirection: "column",
minWidth: 1000,
paddingLeft: 50,
marginLeft: 400,
paddingRight: 30,
paddingBottom: 12,
borderRadius: 15,
}}
span={24}
>
<p style={{ flex: 1, fontWeight: "bold", fontSize: 26 }}>
{repo.name}
</p>
<p style={{ fontWeight: "bold", fontSize: 14 }}>{repo.supplier.companyName}</p>
<p style={{ fontWeight: "bold", fontSize: 14 }}>
{repo.quantityPerUnit}
</p>
<div
style={{
display: "flex",
flexDirection: "row",
justifyContent: "space-between",
alignContent: "flex-end",
}}
>
<p
style={{
fontSize: 20,
fontWeight: "800",
color: "green",
alignSelf: "flex-end",
}}
>
{repo.unitPrice.toFixed(2)}
</p>
<Button type="primary" onClick={() => AddCart(repo)}>
Sepete Ekle
</Button>
</div>
</div>
))}
this is error message
error
this is data:
https://northwind.vercel.app/api/products
edit:
#Tim Roberts found the solution. Only some elements have a supplier so other one's dont have. i took the error message when i try map. I understand now.
I think the error occurs because in some data from the api, the supplier prop doesn't exist.
Your code
<p style={{ fontWeight: "bold", fontSize: 14 }}>{repo.supplier.companyName}</p>
Possible Solution
<p style={{ fontWeight: "bold", fontSize: 14 }}>{repo.supplier && repo.supplier.companyName}</p>

Images shows fine in iOS simulator but when I open android simulator.. everything gets mixed up.. what should I do to solve this issue?

Images show fine in the iOS simulator but when I open the android simulator.. everything gets mixed up.. what should I do to solve this issue? I honestly don't know how to fix this. so please if there's anyone that can solve this.. would really appreciate it.
So this is the Android emulator. I don't know why the image is like this.
this is on iOS simulator, and how it must be.
Home.js
import React from "react";
import {
View,
Text,
Button,
SafeAreaView,
TextInput,
StatusBar,
Platform,
ScrollView,
Image,
imageUri,
StyleSheet,
} from "react-native";
import { MaterialCommunityIcons } from "#expo/vector-icons";
import ProductsList from "../../components/productsList/ProductsList";
import Icon from "react-native-vector-icons/Ionicons";
import { fontSize } from "styled-system";
import Location from "../components/Location";
export default function Search({ navigation }) {
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ flex: 1 }}>
<View
style={{
height: 80,
backgroundColor: "white",
borderBottomWidth: 1,
borderBottomColor: "#dddddd",
}}
>
<View
style={{
flexDirection: "row",
padding: 10,
backgroundColor: "white",
marginHorizontal: 20,
shadowOffset: { width: 0, height: 0 },
shadowColor: "black",
shadowOpacity: 0.2,
borderRadius: 50,
elevation: 1,
}}
>
<Icon name="ios-search" size={20} style={{ marginRight: 10 }} />
<TextInput
underlineColorAndroid="transparent"
placeholder="City, airport, adrerss, or hotel"
placeholderTextColor="grey"
style={{ flex: 1, fontWeight: "700", backgroundColor: "white" }}
/>
</View>
</View>
<ScrollView
horizontal={true}
showsHorizontalScrollIndicator={false}
scrollEventThrottle={16}
>
<View style={{ height: 180, width: 50 }}>
<Image source={require("../home/homepage.jpeg")} />
</View>
</ScrollView>
<ScrollView scrollEventThrottle={16}>
<View style={{ flex: 1, backgroundColor: "white", paddingTop: 20 }}>
<Text
style={{
alignItems: "center",
fontSize: 24,
fontWeight: "700",
paddingHorizontal: 20,
marginLeft: 100,
borderColor: "grey",
height: 50,
width: 230,
shadowOpacity: 0.5,
borderWidth: 0.5,
paddingTop: 10,
backgroundColor: "lightblue",
}}
>
FIND YOUR RIDE
</Text>
<View style={{ height: 130, marginTop: 20 }}>
<ScrollView
horizontal={true}
showsHorizontalScrollIndicator={false}
>
<Location
imageUri={require("../home/nicosia.jpg")}
name="Nicosia"
/>
<Location
imageUri={require("../home/kyrenia.jpg")}
name="Kyrenia"
/>
<Location
imageUri={require("../home/famagusta.jpg")}
name="Famagusta"
/>
<Location
imageUri={require("../home/lefke.png")}
name="Lefke"
/>
</ScrollView>
</View>
<View style={{ marginTop: 40, paddingHorizontal: 20 }}>
<View>
<Text
style={{
fontSize: 24,
fontWeight: "700",
paddingLeft: 40,
}}
>
<View>
<MaterialCommunityIcons
name="face-agent"
size={30}
style={{ paddingLeft: 10, color: "lightblue" }}
/>
</View>
24/7 customer support
</Text>
<Text
style={{ paddingLeft: 80, marginTop: 20, marginBottom: 25 }}
>
{
"Rest easy knowing that everyone in \nthe Rent in cars community is screened, \nand 24/7 customer support and \nroadside assistant are just a tap away."
}
</Text>
</View>
<View>
<Text
style={{
fontSize: 24,
fontWeight: "700",
paddingLeft: 40,
}}
>
<View>
<MaterialCommunityIcons
name="car"
size={30}
style={{
paddingLeft: 10,
color: "lightblue",
marginTop: 20,
}}
/>
</View>
Endless options
</Text>
<Text
style={{ paddingLeft: 80, marginTop: 20, marginBottom: 25 }}
>
{
"Choose from hundreds of models\nyou won't find anywhere else. Pick it \nup or get it delivered where you \nwant it."
}
</Text>
</View>
<View>
<Text
style={{
fontSize: 24,
fontWeight: "700",
paddingLeft: 40,
}}
>
<View>
<MaterialCommunityIcons
name="security"
size={30}
style={{ paddingLeft: 10, color: "lightblue" }}
/>
</View>
Drive confidently
</Text>
<Text style={{ paddingLeft: 80, marginTop: 20 }}>
{
"Drive confidently with your choice \nof protection plans - all plans \ninclude varying levels of third party \nliability insurance from Liberty \nMutual and physical damage \nprotection from Rent in Car that caps\nyour out of pocket responsibility for \ndamage to your host's car during \nyour trip."
}
</Text>
</View>
</View>
</View>
</ScrollView>
</View>
</SafeAreaView>
);
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
red: {
color: "red",
},
});
}
Define width and height and resizeMode :
<View style={{width:"100%", height:180}}>
<Image
style={{
width: "100%",
height: 180
}}
resizeMode="cover"
source={require("../home/homepage.jpeg")}
/>
/>

React - how to apply local storage for hook value

I use the react-range package for personal purposes of my project, the problem is that I cannot save the value when the page is refreshed, I tried to use the local storage but I could not
As you understand, I need to save the value using local storage, in addition, I will leave a link to mine on codesandbox link
SideBarBlurChange.jsx
import React, {useEffect, useState} from "react";
import {getTrackBackground, Range} from "react-range";
const STEP = 0.1;
const MIN = 0;
const MAX = 100;
export default function SideBarBlurChange(props) {
const [values, SetValues] = useState([20])
const SaveChanges = () => {
alert(values)
}
return (
<>
<div
style={{
display: "flex",
justifyContent: "center",
flexWrap: "wrap",
}}
>
<Range
values={values}
step={STEP}
min={MIN}
max={MAX}
onChange={(values) => SetValues(values)}
renderTrack={({ props, children }) => (
<div
onMouseDown={props.onMouseDown}
onTouchStart={props.onTouchStart}
style={{
...props.style,
height: "36px",
display: "flex",
width: "100%"
}}
>
<div
ref={props.ref}
style={{
height: "5px",
width: "100%",
borderRadius: "4px",
background: getTrackBackground({
values: values,
colors: ["#548BF4", "#ccc"],
min: MIN,
max: MAX
}),
alignSelf: "center"
}}
>
{children}
</div>
</div>
)}
renderThumb={({ props, isDragged }) => (
<div
{...props}
style={{
...props.style,
height: "42px",
width: "42px",
borderRadius: "4px",
backgroundColor: "#FFF",
display: "flex",
justifyContent: "center",
alignItems: "center",
boxShadow: "0px 2px 6px #AAA"
}}
>
<div
style={{
height: "16px",
width: "5px",
backgroundColor: isDragged ? "#548BF4" : "#CCC"
}}
/>
</div>
)}
/>
<output style={{ marginTop: "30px" }} id="output">
{values[0].toFixed(1)}
</output>
<button onClick={() => SaveChanges()}>Save</button>
</div>
</>
);
}
I think your main problem was that localStorage doesn't store anything besides strings. You're going to want to parseInt then check to make sure localStorage isn't null. Can you try this and see if it works?
const ls = parseInt(window.localStorage.getItem('values'));
const [values, SetValues] = useState(ls ? [ls] : [20]);
const SaveChanges = () => {
alert(values);
localStorage.setItem('values', values);
}

Categories

Resources