I am getting data which is an array of objects from the store. In useState I want to set an array of data.length size all set to false initially. But when I set the value it returns an empty array [] for each of the state variable I set. I also tried updating the state in the useeffect but nothing works. I am unable to figure out what is the issue here.
function Datatable() {
let data = useSelector((state) => state.dish);
console.log(data.length)
const [clicked1, setClicked1] = useState(new Array(data.length).fill(false));
const [clicked2, setClicked2] = useState(new Array(data.length).fill(false));
const [clicked3, setClicked3] = useState(new Array(data.length).fill(false));
const dispatch = useDispatch();
function setAllStates() {
setClicked1(new Array(data.length).fill(false));
setClicked2(new Array(data.length).fill(false));
setClicked3(new Array(data.length).fill(false));
}
useEffect(() => {
setAllStates();
}, []);
image of console the data
Here is my jsx where i am creating the table
<TableBody>
{data.map((row, index) => (
<TableRow
key={row.id}
sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
>
<TableCell component="th" scope="row">
<img width={150} height={100} src={row.image} />
</TableCell>
<TableCell align="right">{row.dishName}</TableCell>
<TableCell align="right">
{clicked1[index] == false ? (
<>
<Button
onClick={() => handleOnclick("Rank 1", index, row)}
>
Rank 1
</Button>
</>
) : (
<Typography>Selected</Typography>
)}
</TableCell>
Here is the image of the table
in console data.length is showing 0 two times and then 30. I am populating the data in the reducers in its parent component. But still all the arrays are undefined. And in the table all i am showing in the data table are undefined. (Note: I am creating a table of length data.length. data.image, data.description are showing in the table only the buttons that are showing only when clicked1[index] == false are not defined.
Unless data.length is 0, this gotta work.
function Datatable() {
const data = useSelector((state) => state.dish);
const [clicked1, setClicked1] = useState();
const [clicked2, setClicked2] = useState();
const [clicked3, setClicked3] = useState();
const dispatch = useDispatch();
function setAllStates(size) {
const newArray = new Array(size).fill(false);
setClicked1(newArray);
setClicked2(newArray);
setClicked3(newArray);
}
useEffect(() => {
if(data) setAllStates(data.length);
}, [data]);
}
Your code seems fine.
Possible bug may be -> data.length being 0.
To check add console.log(data.length) after data is set.
Now the code:
let data = useSelector((state) => state.dish);
console.log(data.length) // if this is zero , this is causing empty array
const [clicked1, setClicked1] = useState(new Array(data.length).fill(false));
...
Edit:
To ensure the latest value of data is used. We can use useEffect and add data as dependency which ensures that states are set once the data value is not null.
function Datatable() {
const data = useSelector((state) => state.dish);
const [clicked1, setClicked1] = useState();
const [clicked2, setClicked2] = useState();
const [clicked3, setClicked3] = useState();
const dispatch = useDispatch();
function setAllStates(size) {
const newArray = new Array(size).fill(false);
setClicked1(newArray);
setClicked2(newArray);
setClicked3(newArray);
}
useEffect(() => {
if(data) setAllStates(data.length);
}, [data]);
}
Code credits: #dr0nda
Related
I've a weird behavior here.
I'm trying to update a parent component from a child.
I've thus something like this for the child:
const LabelList = ({editable, boardLabels, cardLabels, size='normal', udpateCardLabelsHandler}) => {
return (
<DropDownPicker
labelStyle={{
fontWeight: "bold"
}}
badgeColors={badgeColors}
showBadgeDot={false}
items={items}
multiple={true}
open={open}
onChangeValue={(value) => udpateCardLabelsHandler(value)}
value={value}
setOpen={setOpen}
setValue={setValue} />
)
}
And, for the parent, something like this:
const CardDetails = () => {
const [updatedCardLabels, setUpdatedCardLabels] = useState([])
const [card, setCard] = useState({})
const [editMode, setEditMode] = useState(false)
// Handler to let the LabelList child update the card's labels
const udpateCardLabelsHandler = (values) => {
const boardLabels = boards.value[route.params.boardId].labels
const labels = boardLabels.filter(label => {
return values.indexOf(label.id) !== -1
})
console.log('updated labels',labels)
setUpdatedCardLabels(labels)
}
return (
<View style={{zIndex: 10000}}>
<Text h1 h1Style={theme.title}>
{i18n.t('labels')}
</Text>
<LabelList
editable = {editMode}
boardLabels = {boards.value[route.params.boardId].labels}
cardLabels = {card.labels}
udpateCardLabelsHandler = {udpateCardLabelsHandler} />
</View>
)
And, this just doesn't work: As soon as I try changing something in the DropDownPicker the application hangs. The console.log statement isn't even executed and no errors show up in my expo console.
What's strange is that if I change the updateCardLabels state to be a boolean for example, everything works ok (eg: the console.log statement is executed):
const [updatedCardLabels, setUpdatedCardLabels] = useState(false)
// Handler to let the LabelList child update the card's labels
const udpateCardLabelsHandler = (values) => {
const boardLabels = boards.value[route.params.boardId].labels
const labels = boardLabels.filter(label => {
return values.indexOf(label.id) !== -1
})
console.log('updated labels',labels)
setUpdatedCardLabels(true)
}
Please note that updatedCardLabels isn't used anywhere: it's a dummy variable that I'm just using to debug this issue (to make sure I was not ending in some endless render loop or something similar).
For the sake of completeness, here's what labels looks like at line console.log('updated labels',labels) (please not that I can only see this value when doing setUpdatedCardLabels(true) as otherwise, when the code does setUpdatedCardLabels(labels), the console.log statement is not executed, as mentioned earlier):
updated labels Array [
Object {
"ETag": "a95b2566521a73c5edfb7b8f215948bf",
"boardId": 1,
"cardId": null,
"color": "CC317C",
"id": 9,
"lastModified": 1621108392,
"title": "test-label",
},
]
Does anybody have an explanation for this strange behavior?
Best regards,
Cyrille
So, I've found the problem: It was a side effect of the DrowpDownPicker.
I've solved it by changing my child as follow:
const LabelList = ({editable, boardLabels, cardLabels, size='normal', udpateCardLabelsHandler}) => {
const [open, setOpen] = useState(false);
const [value, setValue] = useState(cardLabels.map(item => item.id));
const theme = useSelector(state => state.theme)
// Updates parent when value changes
useEffect(() => {
if (typeof udpateCardLabelsHandler !== 'undefined') {
udpateCardLabelsHandler(value)
}
}, [value])
return (
<DropDownPicker
labelStyle={{
fontWeight: "bold"
}}
badgeColors={badgeColors}
showBadgeDot={false}
items={items}
multiple={true}
open={open}
value={value}
setOpen={setOpen}
setValue={setValue} />
)
I am new to React (and still new to JS too), and i am trying to build my first React project. I am fetching an API , rendering some items, and building a Search Bar that filters out the items rendered.
My filtering function is more or less working, and inside of it, i store the filtered results in let result , but How i should access those results from the return part (JSX area, i think) to loop over them?
This is my code :
import React, { useState, useEffect } from "react";
import ListItem from "./ListItem";
const List = () => {
const [data, setData] = useState();
const [input, setInput] = useState("");
const onInputChange = (event) => {
setInput(event.target.value);
const value = event.target.value.toLowerCase();
let result = [];
result = data.filter((item) =>
item.name.toLowerCase().includes(value.toLowerCase())
);
setInput(result);
};
useEffect(() => {
const getData = async () => {
const response = await fetch(
"https://rickandmortyapi.com/api/character/"
);
const obj = await response.json();
setData(obj.results);
};
getData();
}, []);
return (
<div>
<input type="text" name={input} onChange={onInputChange}></input>
{data &&
data.map((item) => {
return <ListItem key={item.id} character={item} />;
})}
</div>
);
};
export default List;
So far, I can only loop over input which contains the results, like this input && input.map((item) , but that gives me an empty array when the page is loaded , until i make a search.
You just initialise input as a string so just keep input for keeping input value not result data. You can create another state for keeping result OR put result data back on Data variable.
Here I am showing you to keep result data separate.
import React, { useState, useEffect } from "react";
import ListItem from "./ListItem";
const List = () => {
const [data, setData] = useState();
const [searchResult, setSearchResult] = useState();
const [input, setInput] = useState("");
const onInputChange = (event) => {
setInput(event.target.value);
const value = event.target.value.toLowerCase();
let result = [];
result = data.filter((item) =>
item.name.toLowerCase().includes(value.toLowerCase())
);
setSearchResult(result);
};
useEffect(() => {
const getData = async () => {
const response = await fetch(
"https://rickandmortyapi.com/api/character/"
);
const obj = await response.json();
setData(obj.results);
};
getData();
}, []);
return (
<div>
<input type="text" name={input} onChange={onInputChange}></input>
{input===""? data &&
data.map((item) => {
return <ListItem key={item.id} character={item} />;
}):
searchResult &&
searchResult.map((item) => {
return <ListItem key={item.id} character={item} />;
})
}
</div>
);
};
export default List;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
This is separating your original data and search result different.
You need to use a variable to store data after filter:
const [data, setData] = useState([]);
const onInputChange = (event) => {
setInput(event.target.value);
};
const result = data.filter((item) =>
item.name.toLowerCase().includes(input.toLowerCase())
);
return (
...
{result?.map((item) => {
<ListItem key={item.id} character={item} />;
})}
...
)
One possible solution would be to filter while rendering,
In this scenario you would only need to save the the input value (onInputChange):
const onInputChange = (event) => {
setInput(event.target.value);
};
Then while rendering you would need to add the filtering logic:
{ // if input is not empty
data
.filter(item => item.name.includes(input.toLowerCase()))
.map((item) => {
return <ListItem key={item.id} character={item} />;
})
i'am learning TS yet and I trying to create an application where I get data from API, show results and if someone click on item, it shows a modal with more details, but i'am trouble cause basically my component doesn't render... Look at my code =) !
import IMovie from "../../models/movie.model";
import Modal from "../modal/Modal";
import "./style";
import {
ResultsBody,
ResultsContainer,
TitleResult,
MovieStats,
MovieCover,
MovieStatsDescription,
} from "./style";
interface ISearch {
search?: string;
}
const URL =
"#";
const Results = ({ search }: ISearch) => {
const [data, setData] = React.useState<IMovie[]>([]);
const [currentPage, setCurrentPage] = React.useState(1);
const [dataPerPage] = React.useState(10);
async function getData() {
const response: AxiosResponse<any> = await axios.get(URL);
setData(response.data.results);
}
React.useEffect(() => {
getData();
}, []);
const indexLastData = currentPage * dataPerPage;
const indexFirstData = indexLastData - dataPerPage;
const currentData = data.slice(indexFirstData, indexLastData);
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
const filteredData = data.filter((results) => {
return results.title.toLowerCase().includes(search!.toLocaleLowerCase());
});
return (
<>
<ResultsContainer>
<TitleResult>
<span>Personagem</span>
<span>Sinopse</span>
<span>Data</span>
</TitleResult>
{!search
? currentData.map((item) => (
<ResultsBody
key={item.id}
// onClick={() => {
// selectedMovie(item);
// }}
>
<MovieCover
src={`https://image.tmdb.org/t/p/w185${item.poster_path}`}
alt="poster"
/>
<MovieStats style={{ fontWeight: `bold` }}>
{item.title}
</MovieStats>
<MovieStatsDescription>{item.overview}</MovieStatsDescription>
<MovieStats>{item.release_date}</MovieStats>
</ResultsBody>
))
: filteredData.map((item) => (
<ResultsBody key={item.id}>
<MovieCover
src={`https://image.tmdb.org/t/p/w185${item.poster_path}`}
alt="poster"
/>
<MovieStats style={{ fontWeight: `bold` }}>
{item.title}
</MovieStats>
<MovieStatsDescription>{item.overview}</MovieStatsDescription>
<MovieStats>{item.release_date}</MovieStats>
</ResultsBody>
))}
</ResultsContainer>
<Modal data={data} /> //HERE IS WHERE I'AM CALLING MY MODAL, I want to pass data here
<Pagination
dataPerPage={dataPerPage}
totalData={data.length}
paginate={paginate}
currentPage={currentPage}
/>
</>
);
};
export default Results;
This is my MODAL component
import React from "react";
import { ModalContainer } from "./style";
import IMovie from "../../models/movie.model";
interface IData {
data: IMovie[];
}
const Modal = ({ data }: IData) => {
console.log(data);
return <ModalContainer>{data.title}</ModalContainer>; //HERE IS NOT WORKING
};
export default Modal;
As you can see guys, I can show all results on console.log, but when I put inside the return the log says ''TypeError: Cannot read property 'title' of undefined''
If someone could help me I'd really appreciate! Thanks a lot =)
Movie vs Array
You are getting the error
'Property 'title' does not exist on type 'IMovie[]'. TS2339
in your Modal component because data is an array of movies. An array doesn't have a title property.
You want the modal to show one movie, so you should only pass it one movie.
interface IData {
data: IMovie;
}
Current Selection
Changing the IData interface fixes the issues in Modal, but creates a new error in Results because we are still passing an array. The correct prop is the data for the movie that was clicked. What movie is that? We need to use a useState hook in order to store that data.
Depending on where you control the open/closed state of the Modal, you may also want to pass an onClose callback that clears the selected movie state.
the state:
const [selected, setSelected] = React.useState<IMovie | null>(null); // is a movie or null
in the movie:
onClick={() => setSelected(item)}
the modal:
{selected === null || (
<Modal
data={selected}
onClose={() => setSelected(null)}
/>
)}
Avoid Duplicated Code Blocks
You are rendering a movie the same way whether it's from currentData or filteredData, so we want to combine those. We could create a shared renderMovie callback or ResultsMovie component to use in both loops, but I think we can actually handle it higher up and just have one loop.
You also want your pagination to reflect the pages of just the matching movies when we are filtering based on a search.
// the matchingMovies is a filtered array when there is a search, or otherwise the entire array
const matchingMovies = search
? data.filter((result) =>
result.title.toLowerCase().includes(search.toLowerCase())
)
: data;
const indexLastData = currentPage * dataPerPage;
const indexFirstData = indexLastData - dataPerPage;
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
// total for the pagination should be based on matchingMovies instead of data
const totalData = matchingMovies.length;
// make the currentData from the matchingMovies
const currentData = matchingMovies.slice(indexFirstData, indexLastData);
There might be some bugs or potential additional improvements but I can't actually run this without your components :)
const Results = ({ search }: ISearch) => {
const [data, setData] = React.useState<IMovie[]>([]);
const [currentPage, setCurrentPage] = React.useState(1);
const [dataPerPage] = React.useState(10);
const [selected, setSelected] = React.useState<IMovie | null>(null); // is a movie or null
async function getData() {
const response: AxiosResponse<any> = await axios.get(URL);
setData(response.data.results);
}
React.useEffect(() => {
getData();
}, []);
// the matchingMovies is a filtered array when there is a search, or otherwise the entire array
const matchingMovies = search
? data.filter((result) =>
result.title.toLowerCase().includes(search.toLowerCase())
)
: data;
const indexLastData = currentPage * dataPerPage;
const indexFirstData = indexLastData - dataPerPage;
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
// make the currentData from the matchingMovies
const currentData = matchingMovies.slice(indexFirstData, indexLastData);
return (
<>
<ResultsContainer>
<TitleResult>
<span>Personagem</span>
<span>Sinopse</span>
<span>Data</span>
</TitleResult>
{currentData.map((item) => (
<ResultsBody key={item.id} onClick={() => setSelected(item)}>
<MovieCover
src={`https://image.tmdb.org/t/p/w185${item.poster_path}`}
alt="poster"
/>
<MovieStats style={{ fontWeight: `bold` }}>{item.title}</MovieStats>
<MovieStatsDescription>{item.overview}</MovieStatsDescription>
<MovieStats>{item.release_date}</MovieStats>
</ResultsBody>
))}
</ResultsContainer>
{selected === null || (
<Modal data={selected} onClose={() => setSelected(null)} />
)}
<Pagination
dataPerPage={dataPerPage}
totalData={matchingMovies.length}
paginate={paginate}
currentPage={currentPage}
/>
</>
);
};
interface ModalProps {
data: IMovie;
onClose: () => void;
}
const Modal = ({ data, onClose }: ModalProps) => {
console.log(data);
return <ModalContainer>{data.title}</ModalContainer>;
};
I'm trying to use local storage to store and array it works but when I reload it resets the array. I have looked through some similar questions and did everything I could understand from the answers provided, so I guessed the problem might be from my code so please help me review it. Thanks in advance
import React, { useState } from 'react'
import Modal from './Modal'
function Boards() {
const [boards, setboards] = useState([]);
const [title, settitle] = useState('');
localStorage.setItem('boards', JSON.stringify(boards));
let storedboards = JSON.parse(localStorage.getItem('boards')) || [];
const handleChange = (e) => {
settitle(e.target.value)
}
const handleSubmit = () => {
if (title.length === 0) {
return;
}
setboards(prev => (
[
...prev,
title
]
))
}
return (
<div>
<ul id="boards">
<BoardList boards={boards} />
</ul>
<Modal title={title} handleChange={handleChange} handleSubmit={handleSubmit} />
</div>
)
}
function BoardList({ boards }) {
const history = useHistory()
return (
<>
{
boards.map((board, index) => (
<li key={index} onClick={() => { history.push('./workspace') }}>
<h3>{board}</h3>
</li>
))}
</>
)
}
export default Boards
It's reseting the array when you reload, because of this:
function Boards() {
// you're creating a state variable with an empty array
const [boards, setboards] = useState([]);
// you're overriding the item `boards` on the local storage
localStorage.setItem('boards', JSON.stringify(boards));
Try a slight change like this:
function Boards() {
// try to load `boards` from the local storage, if null set empty array to the var
const storedboards = JSON.parse(localStorage.getItem("boards")) || [];
// use the above var to create the state variable
// if you have `boards` in the local storage, the value will be the recovered value
// otherwise the initial value for this state will be an empty array
const [boards, setboards] = useState(storedboards);
I'm having an issue where useEffect isn't triggering a re-render based on useState changing or useState isn't changing which isn't triggering useEffect. I noticed this issue once I selected an asset that should update useState as the selected component and then I select another its no problem but once I select an asset that has already been selected.. nothing happens? Any suggestions or anything is greatly appreciated!! Thanks!
export default function SingleAsset({svg, name, size = '60', group}) {
const [assetType, setAssetType] = React.useState(null);
const [officeType, setOfficeType] = React.useState(null);
const [industrialType, setIndustrialType] = React.useState(null);
const [financingType, setFinancingType] = React.useState(null);
const [investmentType, setInvestmentType] = React.useState(null)
const acquistionStatus = useSelector(state => state.Acquisition)
const dispatch = useDispatch()
const classes = useStyles()
React.useEffect(() => {
if(financingType === 'Acquisition') {
const data = {financingType}
dispatch(updateFormData(data))
dispatch(toggleAcquisitionOn())
}
if(financingType) {
if(financingType !== 'Acquisition') dispatch(toggleAcquisitionOff())
const data = {financingType}
dispatch(updateFormData(data))
}
if(industrialType) {
const data = {industrialType}
dispatch(updateFormData(data))
}
if(officeType) {
const data = {officeType}
dispatch(updateFormData(data))
}
if(investmentType) {
const data = {investmentType}
dispatch(updateFormData(data))
console.log(data)
}
if(assetType) dispatch(updateAssetData(assetType))
console.log(financingType)
console.log(officeType)
console.log(industrialType)
console.log(investmentType)
},[investmentType,assetType,officeType,industrialType,financingType])
const handleSelect = (group, name) => {
switch(group) {
case 'main':
setAssetType(name)
break
case 'office':
setOfficeType(name)
break
case 'industrial':
setIndustrialType(name)
break
case 'financing':
setFinancingType(name)
break
case 'investment':
setInvestmentType(name)
break
default:
throw new Error('group not found')
}
}
return (
<Grid
className={classes.container}
item
>
<Grid
container
direction="column"
alignItems="center"
>
<IconButton onClick={() => handleSelect(group, name)}>
<img src={svg} color="white" height={size} />
</IconButton>
<Typography
variant="body1"
color="white"
align="center"
>
{name}
</Typography>
</Grid>
</Grid>
)
}
That's actually an expected behavior.
React uses "shallow comparison" (check this other great question for more on that), which essentially means it'll compare the previous and new value with ===. This is the reason one should not mutate state objects. Because of this, when your code tries to update the state to the same value it already has it won't actually do it... it's the same, so no re-render will be triggered.
To solve this, we can force React to update with some clever coding that will make React detect a state change:
// Setup a new state
const [, updateState] = useState();
// Create a function that will update state with a new object
// This works because {} === {} is always false, making React trigger a re-render
const forceUpdate = useCallback(() => updateState({}), []);
Your sample code would be something like this:
export default function SingleAsset({svg, name, size = '60', group}) {
const [, updateState] = useState();
const forceUpdate = useCallback(() => updateState({}), []);
const [assetType, setAssetType] = React.useState(null);
const [officeType, setOfficeType] = React.useState(null);
const [industrialType, setIndustrialType] = React.useState(null);
const [financingType, setFinancingType] = React.useState(null);
const [investmentType, setInvestmentType] = React.useState(null)
const acquistionStatus = useSelector(state => state.Acquisition)
const dispatch = useDispatch()
const classes = useStyles()
React.useEffect(() => {
if(financingType === 'Acquisition') {
const data = {financingType}
dispatch(updateFormData(data))
dispatch(toggleAcquisitionOn())
}
if(financingType) {
if(financingType !== 'Acquisition') dispatch(toggleAcquisitionOff())
const data = {financingType}
dispatch(updateFormData(data))
}
if(industrialType) {
const data = {industrialType}
dispatch(updateFormData(data))
}
if(officeType) {
const data = {officeType}
dispatch(updateFormData(data))
}
if(investmentType) {
const data = {investmentType}
dispatch(updateFormData(data))
console.log(data)
}
if(assetType) dispatch(updateAssetData(assetType))
console.log(financingType)
console.log(officeType)
console.log(industrialType)
console.log(investmentType)
},[investmentType,assetType,officeType,industrialType,financingType])
const handleSelect = (group, name) => {
switch(group) {
case 'main':
setAssetType(name)
break
case 'office':
setOfficeType(name)
break
case 'industrial':
setIndustrialType(name)
break
case 'financing':
setFinancingType(name)
break
case 'investment':
setInvestmentType(name)
break
default:
throw new Error('group not found')
}
}
return (
<Grid
className={classes.container}
item
>
<Grid
container
direction="column"
alignItems="center"
>
<IconButton onClick={() => {
handleSelect(group, name);
forceUpdate(); // <-- this is were the magic happens
}}>
<img src={svg} color="white" height={size} />
</IconButton>
<Typography
variant="body1"
color="white"
align="center"
>
{name}
</Typography>
</Grid>
</Grid>
)
}
Please note forcing a re-render should be a last resort, re-rendering can be a rather expensive operation and should be handled with care.