React: prevent variables from re-rendering - javascript

i recently found the issue of my problem but it's not solved yet, so i have a variable named data that have a bunch array of objects, i want to move it to global variable so it's not going to re-rendering but i can't because the fetchedData state prevent me from doing this and i can't move my state to global variable,i've tried several method like making a function outside it's component or using react.memo but it solve nothing. is there a way to achieve this?
here's my code Table.js :
import DataTable from "react-data-table-component";
import Columns from "./Columns.js";
...
const Table = () => {
let [page, setPage] = useState(1);
const [fetchedData, setFetchedData] = useState([]);
var [selectedRowsData, setSelectedRowsData] = useState();
const classes = useStyles();
const dispatch = useDispatch();
const checkBoxProps = {
color: "primary",
};
useEffect(() => {
const fetchAPI = async () => {
setFetchedData(
await dispatch(
fetchTableList(
localStorage.getItem("userId"),
localStorage.getItem("auth"),
page
)
)
);
};
fetchAPI();
}, [page]);
const data = [
...fetchedData.map((val, i) => ({
no: val.ROW_NUMBER,
customerId: val.CUSTOMER_ID,
customerName: val.CUSTOMER_NAME,
poDate: val.PO_DATE,
branchId: val.BRANCH_ID,
passangerId: val.PASSANGER_ID,
passangerBank: val.PASSANGER_BANK_NAME,
passangerBankBranch: val.PASSANGER_BANK_BRANCH,
created: val.CREATEBY,
})),
];
const handleChange = (state) => {
console.log(state.selectedRows);
};
return (
<div>
<TableHeader />
<div>
<div>
<DataTable
columns={Columns}
data={data}
selectableRows
selectableRowsComponent={Checkbox}
selectableRowsComponentProps={checkBoxProps}
onSelectedRowsChange={handleChange}
noDataComponent={"Fetching data, please wait..."}
selectableRowsHighlight
customStyles={CustomTableStyle}
conditionalRowStyles={CustomRowBackColor}
dense
/>
<div className={classes.footer}>
<Footer />
<div className={classes.paginationBox}>
<Pagination
nextPage={nextPage}
previousPage={previousPage}
page={page}
setPage={setPage}
/>
</div>
</div>
</div>
</div>
</div>
);
};
export default Table;```

useMemo can be used to control when a given variable inside a functional component is recomputed; e.g.
const data = useMemo(
() => fetchedData.map(val => ({
no: val.ROW_NUMBER,
customerId: val.CUSTOMER_ID,
customerName: val.CUSTOMER_NAME,
poDate: val.PO_DATE,
branchId: val.BRANCH_ID,
passangerId: val.PASSANGER_ID,
passangerBank: val.PASSANGER_BANK_NAME,
passangerBankBranch: val.PASSANGER_BANK_BRANCH,
created: val.CREATEBY,
})),
[fetchedData],
)

Related

Why the filter does not return the list on the initial render?

What I have is a list that was fetched from an api. This list will be filtered based on the input. But at the first render it will render nothing, unless I press space or add anything to the input. Another solution is set the fetched data to the filteredList. But I don't know if it is the right thing to set the fetched data to two arrays.
import React, { useState, useEffect } from "react";
const PersonDetail = ({ person }) => {
return (
<div>
Id: {person.id} <br />
Name: {person.name} <br />
Phone: {person.phone}
</div>
);
};
const App = () => {
const [personsList, setPersonsList] = useState([]);
const [personObj, setPersonObj] = useState({});
const [showPersonDetail, setShowPersonDetail] = useState(false);
const [newPerson, setNewPerson] = useState("");
const [filter, setFilter] = useState("");
const [filteredList, setFilteredList] = useState(personsList);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((data) => {
setPersonsList(data);
//setFilteredList(data) <-- I have to add this to work
console.log(data);
});
}, []);
const handleClick = ({ person }) => {
setPersonObj(person);
if (!showPersonDetail) {
setShowPersonDetail(!showPersonDetail);
}
};
const handleChange = (event) => {
setNewPerson(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
const tempPersonObj = {
name: newPerson,
phone: "123-456-7890",
id: personsList.length + 1,
};
setPersonsList((personsList) => [...personsList, tempPersonObj]);
//setFilteredList(personsList) <-- to render the list again when add new person
setNewPerson(" ");
};
const handleFilter = (event) => {
setFilter(event.target.value);
const filteredList =
event.target.value.length > 0
? personsList.filter((person) =>
person.name.toLowerCase().includes(event.target.value.toLowerCase())
)
: personsList;
setFilteredList(filteredList);
};
return (
<div>
<h2>List:</h2>
Filter{" "}
<input value={filter} onChange={handleFilter} placeholder="Enter" />
<ul>
{filteredList.map((person) => {
return (
<li key={person.id}>
{person.name} {""}
<button onClick={() => handleClick({ person })}>View</button>
</li>
);
})}
</ul>
<form onSubmit={handleSubmit}>
<input
placeholder="Add Person"
value={newPerson}
onChange={handleChange}
/>
<button type="submit">Add</button>
</form>
{showPersonDetail && <PersonDetail person={personObj} />}
</div>
);
};
export default App;
Your filtered list is actually something derived from the full persons list.
To express this, you should not create two apparently independent states in this situation.
When your asynchronous fetch completes, the filter is probably already set and you are just setting personsList which is not the list you are rendering. You are rendering filteredList which is still empty and you are not updating it anywhere, except when the filter gets changed.
To avoid all of this, you could create the filtered list on each rendering and — if you think this is not efficient enough — memoize the result.
const filteredList = useMemo(() =>
filter.length > 0
? personsList.filter((person) =>
person.name.toLowerCase().includes(filter.toLowerCase())
)
: personsList,
[filter, personsList]
);
When the filter input gets changed, you should just call setFilter(event.target.value).
This way, you will always have a filtered list, independent of when your asynchronous person list fetching completes or when filters get updated.
Side note: Writing const [filteredList, setFilteredList] = useState(personsList); looks nice but is the same as const [filteredList, setFilteredList] = useState([]); because the initial value will be written to the state only once, at that's when the component gets initialized. At that time personsList is just an empty array.

Get value from response and transfer to another component in React

I have this handleSubmit that returns me a key (verifyCode) that I should use in another component. How can I pass this verifyCode to another component?
const SendForm = ({ someValues }) => {
const handleSubmitAccount = () => {
dispatch(createAccount(id, username))
.then((response) => {
// I get this value from data.response, its works
const { verifyCode } = response;
})
.catch(() => {
});
};
return(
//the form with handleSubmitAccount()
)
}
export default SendForm;
The other component is not a child component, it is loaded after this submit step. But I don't know how to transfer the const verifyCode.
This is the view where the components are loaded, it's a step view, one is loaded after the other, I need to get the const verifyCode in FormConfirmation
<SendForm onSubmit={handleStepSubmit} onFieldSubmit={handleFieldSubmit} />
<FormConfirmation onSubmit={handleStepSubmit} onFieldSubmit={handleFieldSubmit} />
Does anyone know how I can do this?
You need to move up the state to a component that has both as children and then pass down a function that updates as a prop
import React from "react";
export default function App() {
const [value, setValue] = React.useState(0);
return (
<div className="App">
<Updater onClick={() => setValue(value + 1)} />
<ValueDisplay number={value} />
</div>
);
}
const Updater = (props) => <div onClick={props.onClick}>Update State</div>;
const ValueDisplay = (props) => <div>{props.number}</div>;
Check out the docs here
For more complex component structures or where your passing down many levels you may want to look into reactContext
import React from "react";
//Set Default Context
const valueContext = React.createContext({ value: 0, setValue: undefined });
export default function App() {
const [value, setValue] = React.useState(0);
return (
<div className="App">
{/** Pass in state and setter as value */}
<valueContext.Provider value={{ value: value, setValue }}>
<Updater />
<ValueDisplay />
</valueContext.Provider>
</div>
);
}
const Updater = () => {
/** Access context with hook */
const context = React.useContext(valueContext);
return (
<div onClick={() => context.setValue(context.value + 1)}>Update State</div>
);
};
const ValueDisplay = () => {
/** Access context with hook */
const context = React.useContext(valueContext);
return <div>{context?.value}</div>;
};

react how to not be so repetitive using useState hooks

I am making a form that uses many fields to post the data into a database.
I have over 80 fields like "title, body HTML, price, compare price, vendor, weights", etc.
and my code is very repetitive, is there a way to make my code shorter? I shaved a lot of my code because it's over 600 lines of code and would be too confusing to post the whole thing
I made 2 separate functions handleChange and selectHandler as little helpers to get the value of the dropdowns datalist inputs to be stored into state... the values have to be stored in separate states as I need each one to do an axios call to store its specific fields into the right data field.
import React, { useState } from "react";
function handleChange(e, setter) {
return setter({ value: e.target.value });
}
function selectHandler(setter) {
return (
<>
<input
list="headers"
placeholder="Select one"
onChange={(e) => handleChange(e, setter)}
/>
{/* headers comes from mapped api in another file */}
<datalist id="headers">{headers}</datalist>
</>
);
}
function PushToDB() {
const [showExtraImageInputs, setShowExtraImageInputs] = useState(false);
const [titleHeader, setTitleHeader] = useState();
const [handleHeader, setHandleHeader] = useState();
const [descriptionHtmlHeader, setDescriptionHtmlHeader] = useState();
const [image1Header, setImage1Header] = useState();
const [image2Header, setImage2Header] = useState();
const [altText1, setAltText1] = useState();
const [altText2, setAltText2] = useState();
return (
<>
<form onSubmit={(e) => e.preventDefault()}>
// each label uses the helpers to get the dropdown values and store it in state
<label>Title: {selectHandler(setTitleHeader)}</label>
<label>Body html: {selectHandler(setDescriptionHtmlHeader)}</label>
<label>Handle: {selectHandler(setHandleHeader)}</label>
<label>Image: {selectHandler(setImage1Header)}</label>
<label>Img alt text: {selectHandler(setAltText1)}</label>
{/* ADD MORE IMAGES */}
{showExtraImageInputs && (
<>
<div>Image 2: {selectHandler(setImage2Header)}</div>
<div>Img alt text 2: {selectHandler(setAltText2)}</div>
</>
)}
</form>
</>
);
}
export default PushToDB;
this is how the axios data looks like. as you can see I need each value from state. and again, its over 80 fields.
useEffect(() => {
if (pushState && apiData) {
let productValues = apiData.data.data;
productValues.map((e) => {
let url = `url`;
return axios
.get(url)
.then((res) => {
if (res) {
// if the data is already in db, do not push
if (res.data.products.length === 0)
// if there is no data then push data
return setProductData({
variables: {
// values from state
title: e[titleHeader?.value],
descriptionHtml: e[descriptionHtmlHeader?.value],
handle: e[handleHeader?.value],
img1: e[image1Header?.value] ?? "",
alt1: e[altText1?.value],
img2 : e[image2Header?.value] ?? '',
alt2: e[altText2?.value],
img3: e[image3Header?.value] ?? '',
// and so on
},
});
}
// this is the logger of whats being pushed into the database
})
.then((res) => {
if (res)
return axios.post("http://localhost:4000/api/v1/Extradb", {
data: {
title: res?.data?.productCreate?.product?.title,
handle: res?.data?.productCreate?.product?.handle,
item_id: res?.data?.productCreate?.product?.id,
},
});
});
});
}
}, []);
came out with a solution... I just needed to make an object
function App() {
const [userInputs, setUserInputs] = useState({})
function handleChange(e) {
const { value, name } = e.target
setUserInputs(prevState => ({
...prevState,
[name]: value
}))
}
function handleInputNaming(name) {
let capitilizedWord = name.charAt(0).toUpperCase() + name.slice(1);
return (<input placeholder={capitilizedWord} name={name} value={userInputs[name]} onChange={handleChange} />)
}
return (
<div className="App">
{handleInputNaming('title')}
{handleInputNaming('handle')}
{handleInputNaming('image')}
</div>
);
}
export default App;

There's a bug with Search and Pagination in React

I'm building my site in React and I have created pagination and search. When I search for something on the site, it only works when after that I go to another page. I think this is due to the fact that Softwares and Pagination are in the same component.
Then I tried lifting-state-up, but I got an error: React Minified Error # 31.
Here's Pagination component:
const Paginator = ({
total, // Total records
startPage = 1,
totalPages = null,
onMovePage = null,
}) => {
...
return (
<>
<section id={styles.paginator}>
<Header/>
...
{range(1, totalPages+1).map(p => (
<PagItem key={p} handleClick={ () => {setCurrentPage(p); onMovePage && onMovePage({currentPage: p})} } title={p} name={p} />
))}
...
</section>
</>
);
};
Here's Softwares component:
const Softwares = ({ search }) => {
const [softwares, setSoftwares] = useState([]);
const [total, setTotal] = useState(null);
const [totalPages, setTotalPages] = useState(null);
const [valid, setValid] = useState(false);
const fetchData = async ({ currentPage }) => {
const SEARCH = search ? `?search=${search}` : '';
const CURRENT_PAGE = currentPage && SEARCH === '' ? `?page=${currentPage}` : '';
const response = await fetch(`http://127.0.0.1:8000/api/software/${CURRENT_PAGE}${SEARCH}`);
const data = await response.json();
setSoftwares(data.results);
setTotal(data.count);
setTotalPages(data.total_pages);
setValid(true);
}
useEffect(() => {
fetchData({ currentPage: 1 });
}, []);
return (
<>
{
valid &&
<section className={styles.softwares}>
<Header header={"new softwares"} />
{softwares.map(s => (
<Article key={s.id} pathname={s.id} title={s.title} image={s.image} pubdate={s.pub_date} icon={s.category.parent.img} categoryID={s.category.id} categoryName={s.category.name} dCount={s.counter} content={s.content} />
))}
<Paginator totalPages={totalPages} total={total} onMovePage={fetchData} />
</section>
}
</>
);
};
SearchForm in Header component:
const Header = ({ handleChange, handleClick }) => {
return (
...
<SearchForm handleChange={handleChange} handleClick={handleClick} />
...
);
};
const SearchForm = ({ style, handleChange, handleClick }) => {
return (
<div style={style}>
<form>
<input
type="text"
onChange={handleChange}
/>
<SearchButton onClick={handleClick} />
<small>ENTER</small>
</form>
</div>
);
};
const SearchButton = ({onClick }) => {
return (
<button type="button" onClick={onClick}>
<FontAwesomeIcon icon={faSearch} />
</button>
);
};
And part of Search in App component:
const App = () => {
...
// Search
const [search, setSearch] = useState('');
const [shouldFetch, setShouldFetch] = useState(false);
const handleChange = (e) => {
setSearch(e.target.value);
}
useEffect(() => {
if (shouldFetch) {
(async () => {
const response = await fetch(`http://127.0.0.1:8000/api/software/?search=${search}`);
const data = await response.json();
setShouldFetch(false);
})()
}
}, [shouldFetch]);
const handleClick = () => setShouldFetch(true);
return (
<div className="App">
<Header handleChange={handleChange} handleClick={handleClick} />
...
<Switch>
<Route path="/" exact render={props => <Softwares {...props} search={search} />} />
</Switch>
{/* Actually I'd like to use Paginator here, but it
throws the error: React Minified Error # 31 */}
...
</div>
);
}
So, how can this be done?
The problem is your useEffect dependencies (or lack thereof).
Here's the relevant section of the code:
const Softwares = ({ search }) => {
const [softwares, setSoftwares] = useState([]);
const [total, setTotal] = useState(null);
const [totalPages, setTotalPages] = useState(null);
const [valid, setValid] = useState(false);
const fetchData = async ({ currentPage }) => {
const SEARCH = search ? `?search=${search}` : '';
const CURRENT_PAGE = currentPage && SEARCH === '' ? `?page=${currentPage}` : '';
const response = await fetch(`http://127.0.0.1:8000/api/software/${CURRENT_PAGE}${SEARCH}`);
const data = await response.json();
setSoftwares(data.results);
setTotal(data.count);
setTotalPages(data.total_pages);
setValid(true);
}
useEffect(() => {
fetchData({ currentPage: 1 });
}, []);
The empty dependency array means that you are running the effect that calls fetchData one time when the component mounts. Clicks in the Pagination component will call the fetchData function directly. Changes to search do not cause fetchData to re-run. The data depends on the search so search should be a dependency.
The fetchData function is fine in this component. The state that I would recommend lifting up is to lift the currentPage up from Pagination into Softwares. The onMovePage callback can just update the currentPage state. That way you can call fetchData only through your effect and run the effect whenever either search or currentPage changes.
const Softwares = ({ search }) => {
const [softwares, setSoftwares] = useState([]);
const [total, setTotal] = useState(null);
const [totalPages, setTotalPages] = useState(null);
const [valid, setValid] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
useEffect(() => {
// defining the function inside of the useEffect
// lets eslint exhaustive dependency checks work their magic
const fetchData = async () => {
const SEARCH = search ? `?search=${search}` : '';
const CURRENT_PAGE = currentPage && SEARCH === '' ? `?page=${currentPage}` : '';
const response = await fetch(`http://127.0.0.1:8000/api/software/${CURRENT_PAGE}${SEARCH}`);
const data = await response.json();
setSoftwares(data.results);
setTotal(data.count);
setTotalPages(data.total_pages);
setValid(true);
}
// need to define and call in separate steps when using async functions
fetchData();
}, [currentPage, search]);
return (
...
<Paginator page={currentPage} totalPages={totalPages} total={total} onMovePage={setCurrentPage} />
...
);
};

Passing data to sibling components with react hooks?

I want to pass a variable username from sibling1 component to sibling2 component and display it there.
Sibling1 component:
const sibling1 = ({ usernameData }) => {
// I want to pass the username value I get from input to sibling2 component
const [username, setUsername] = useState("");
const handleChange = event => {
setUsername(event.target.value);
};
return (
<Form.Input
icon='user'
iconPosition='left'
label='Username'
onChange={handleChange}
/>
<Button content='Login' onClick={handleClick} />
)
}
export default sibling1;
Sibling2 component:
export default function sibling2() {
return (
<h1> Here is where i want to display it </h1>
)
}
You will need to handle your userName in the parent of your siblings. then you can just pass setUsername to your sibling1, and userName to your sibling2. When sibling1 use setUsername, it will update your parent state and re-render your sibling2 (Because the prop is edited).
Here what it looks like :
const App = () => {
const [username, setUsername] = useState('Default username');
return (
<>
<Sibling1 setUsername={setUsername} />
<Sibling2 username={username} />
</>
)
}
const Sibling2 = ({username}) => {
return <h1> Helo {username}</h1>;
}
const Sibling1 = ({setUsername}) => {
return <button onClick={setUsername}>Set username</button>;
}
In parent of these two components create a context where you will store a value and value setter (the best would be from useState). So, it will look like this:
export const Context = React.createContext({ value: null, setValue: () => {} });
export const ParentComponent = () => {
const [value, setValue] = useState(null);
return (
<Context.Provider value={{value, setValue}}>
<Sibling1 />
<Sibling2 />
</Context.Provider>
);
Then in siblings you are using it like this:
const Sibling1 = () => {
const {setValue} = useContext(Context);
const handleChange = event => {
setValue(event.target.value);
};
// rest of code here
}
const Sibling2 = () => {
const {value} = useContext(Context);
return <h1>{value}</h1>;
}
best way: React Context + hooks
you can use React Context. take a look at this example:
https://codesandbox.io/s/react-context-api-example-0ghhy

Categories

Resources