So I'have a initial state in my wrapper component with two items
const initialData = {
first: clubData.applications[0].invoice_url,
second: clubData.applications[0].invoice_url_2,
};
const [invoiceFiles, setInvoiceFiles] = useState(initialData);
, the component has 2 childs and each child gets one of the items as file prop and also functions to change the state accroding to which property from state they use.
<AddInvoice
admin={admin}
clubData={clubData}
addFile={(file) => addFile("first", file)}
file={invoiceFiles.first}
deleteFile={() => deleteFile("first")}
invoiceUrl={clubData.applications[0].invoice_url}
/>
when i invoke the addFile function from AddInvoice component nothing happens in wrapper components, not even the useEffect function is called.Anyone know's why it is happening?
Here's my full wrapper code:
const AddInvoiceWrapper = ({ clubData, admin }) => {
const initialData = {
first: clubData.applications[0].invoice_url,
second: clubData.applications[0].invoice_url_2,
};
const [invoiceFiles, setInvoiceFiles] = useState(initialData);
const addFile = (index, file) => {
let newFiles = invoiceFiles;
newFiles[index] = file;
console.log(newFiles);
setInvoiceFiles(newFiles);
};
const deleteFile = (index) => {
let newFiles = invoiceFiles;
newFiles[index] = null;
setInvoiceFiles(newFiles);
};
useEffect(() => {
console.log("invoice files changed!");
}, [invoiceFiles]);
return (
<Row>
<Column>
<Paragraph>Dodaj fakturÄ™ (dev) </Paragraph>
<AddInvoice
admin={admin}
clubData={clubData}
addFile={(file) => addFile("first", file)}
file={invoiceFiles.first}
deleteFile={() => deleteFile("first")}
invoiceUrl={clubData.applications[0].invoice_url}
/>
</Column>
{invoiceFiles.first != null ? (
<Column>
<Paragraph>Dodaj koretkÄ™ faktury</Paragraph>
<AddInvoice
admin={admin}
clubData={clubData}
addFile={(file) => addFile("second", file)}
file={invoiceFiles.second}
deleteFile={() => deleteFile("second")}
invoiceUrl={clubData.applications[0].invoice_url_2}
/>
</Column>
) : null}
</Row>
);
};
export default AddInvoiceWrapper;
And this is also function in child components that triggers function in wrapper:
const handleChange = (e) => {
e.preventDefault();
addFile(e.target.files[0]);
};
The data is passed with no problems and in addFile function i get the proper new object but when i use "setInvoiceFiles" nothing happens, i see the change only when i make some changes in the code and the hot reload automaticily runs and refreshes the state.
Because the pointers are the same, React will not consider this a new data, and will not re-render. try setInvoiceFiles([...newFiles]); instead.
you can read about spread operator (...) here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
When you create newFiles like this: let newFiles = invoiceFiles;
newFiles will have the same reference as invoiceFiles. When React compare object, it compares their references, since your newFiles and invoiceFiles have same reference (even though inner values are different), React won't mark it as an update so it won't trigger re-render or call useEffect
The solution is simple: Just change the line I mentioned to this:
let newFiles = {...invoiceFiles};
This time, newFiles will be a totally new variable with different reference.
You need to return new array to update state:
const addFile = (index, file) => {
setInvoiceFiles((preState) =>
preState.map((item, i) => {
return index === i ? file : item;
}),
);
};
Related
I'm trying to rewrite this code from class to a function. I've never used classes but I got this test code for a calendar app while learning react native but I seem to get stuck somewhere when I'm trying to replace componentDidUpdate to useEffect.
This is the old code:
export default class DaysInMonth extends React.PureComponent{
state = {
lastCalendarDayIndex: 0,
currentCalendarDayIndex: 0,
}
changeCurrentCalendarDayIndex = (index) => {
this.setState({
currentCalendarDayIndex: index
})
}
componentDidUpdate(prevProps, prevState){
if(this.state.currentCalendarDayIndex !== prevState.currentCalendarDayIndex){
this.setState({
lastCalendarDayIndex: prevState.currentCalendarDayIndex
})
}
}
render(){
return(
<>
{
this.props.row_days_array.map((rowData, index) => (
<CalendarRow
key = {'calendar row ' + index}
rowData = {rowData}
lastCalendarDayIndex = {this.state.lastCalendarDayIndex}
changeCurrentCalendarDayIndex = {this.changeCurrentCalendarDayIndex}
month_index = {this.props.month_index}
current_month_index = {this.props.current_month_index}
chooseDifferentMonth = {this.props.chooseDifferentMonth}
/>
))
}
</>
)
}
}
And this is the new code everything works except for some functions which has to do with the useEffect, I don't understand what properties I should add to get the same functionality as before. Thanks
export default function DaysInMonth({row_days_array, month_index, current_month_index, chooseDifferentMonth}) {
const [lastCalendarDayIndex, setLastCalendarDayIndex] = useState(0)
const [currentCalendarDayIndex, setCurrentCalendarDayIndex] = useState(0)
const changeCurrentCalendarDayIndex = (index) => {
setCurrentCalendarDayIndex(index)
}
useEffect(() => {
if(currentCalendarDayIndex !== currentCalendarDayIndex){
setLastCalendarDayIndex(currentCalendarDayIndex)
}
},[]);
return (
<>
{row_days_array.map((rowData, index) => (
<CalendarRow
key = {'calendar row ' + index}
rowData = {rowData}
lastCalendarDayIndex = {lastCalendarDayIndex}
changeCurrentCalendarDayIndex = {changeCurrentCalendarDayIndex}
month_index = {month_index}
current_month_index = {current_month_index}
chooseDifferentMonth = {chooseDifferentMonth}
/>
))}
</>
)
}
What this does:
useEffect(() => {
if(currentCalendarDayIndex !== currentCalendarDayIndex){
setLastCalendarDayIndex(currentCalendarDayIndex)
}
},[]);
It runs the code inside useEffect every time the array changes. Because it's an empty array it will just run once (once the component mounts, this is basically the old ComponentDidMount), to mimic the behaviour of ComponentDidUpdate you need to keep track of the props so it should be a matter of passing them into the array (so React can track when it changes):
useEffect(() => {
if(currentCalendarDayIndex !== currentCalendarDayIndex){
setLastCalendarDayIndex(currentCalendarDayIndex)
}
},[props]);
It's probably easier to change the destructuring you have in the component definition {row_days_array, month_index, current_month_index, chooseDifferentMonth} to props and then destructure a bit bellow, so you can use the whole object in you useEffect array
You can pass a callback in setState to access previous state, and pass currentCalendarDayIndex in useEffect dependency to update lastedCalendarState every currentCalendar changes. Hope this can help!
useEffect(() => {
setLastCalendarDayIndex((prevCalendarDayIndex) =>
prevCalendarDayIndex !== currentCalendarDayIndex
? currentCalendarDayIndex
: prevCalendarDayIndex)
}, [currentCalendarDayIndex])
I have this situation:
I want to update some state (an array) which is used to map different React components.
Those componentes, have their own handleUpdate.
But when I call to handleUpdate the state that I need to use is empty. I think is because each handler method was mounted before the state was filled with data, but then, how could I ensure or use the data in the handler? In other words, the handler needs to update the state that fill it's own state:
const [data, setData] = useState([]);
const [deliver, setDeliver] = useState({items: []});
const handleUpdate = (value, position) => {
// This set works
setDeliver({
items: newItems
});
// This doesn't work because "data" is an empty array - CRASH
setData(data[position] = value);
};
useEffect(() => {
const dataWithComponent = originalData.map((item, i) => ({
...item,
entregado: <SelectorComponent
value={deliver?.items[i].delivered}
key={i}
onUpdate={(value) => handleUpdate(value, i)}
/>
}));
setData(dataWithComponent); // This is set after <SelectComponent is created...
}
}, [originalData]);
The value that you pass don't come from originalData, so the onUpdated don't know what it's value
You run on originalData using map, so you need to pass item.somthing the the onUpdate function
const dataWithComponent = originalData.map((item, i) => ({
...item,
entregado: <SelectorComponent
value={deliver?.items[i].delivered} // you can't use items use deliver.length > 0 ? [i].delivered : ""
key={i}
onUpdate={() => handleUpdate("here you pass item", i)}
/>
}));
I'm not sure, but I think you can do something like that. I hope you get some idea to work it.
// This doesn't work because "data" is an empty array - CRASH
let tempData = [...data].
tempData[position] = value;
setData(tempData);
I'm using useRef to hold the reference of a function that is invoked from a child component (TaskItem) when it is clicked on:
UserTask -> TaskList -> TaskItem
// UserTask.js
const [detailsVisible, setDetailsVisible] = useState(false)
const [selectedTask, setSelectedTask] = useState({})
const openTask = (id) =>{
const task = props.tasks.find(task => task.id === id);
setDetailsVisible(true);
setSelectedTask(task);
}
const openTaskRef = useRef(openTask);
const openTaskHandler = useCallback(id =>{
openTaskRef.current(id);
}, []);
return (
<React.Fragment>
<TaskList
tasks={props.tasks}
onClick={openTaskHandler}
/>
<Modal visible={detailsVisible} onClose={()=> setDetailsVisible(false)}>
<Comments items={selectedTask.comments || []} />
</Modal>
</React.Fragment>
)
The list of tasks arrives via redux->props a few seconds after they are fetched from an API:
// Still UserTask.js
useEffect(()=>{
fetchTasks()
}, [fetchTasks])
const mapDispatchToProps = dispatch =>{
return {
fetchTasks: ()=> dispatch(fetchTasks())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(UserTasks)
Now, my problem is that when the component (UserTask) is rendered the first time, the 'openTaskRef' gets created with a context in which props.tasks is empty (since the API request hasn't been issued yet). I need to use the useRef/useCallback combination to avoid re-rendering of TaskItems when the props.tasks list is updated after an item is removed (a scenario not described in the code above).
How can I control this scenario? How can I update the reference to openTask to include the most recent list of tasks?
Thanks.
The parent component contains an array of objects.
It maps over the array and returns a child component for every object, populating it with the info of that object.
Inside each child component there is an input field that I'm hoping will allow the user to update the object, but I can't figure out how to go about doing that.
Between the hooks, props, and object immutability, I'm lost conceptually.
Here's a simplified version of the parent component:
const Parent = () => {
const [categories, setCategories] = useState([]);
useEffect(()=>{
// makes an axios call and triggers setCategories() with the response
}
return(
categories.map((element, index) => {
return(
<Child
key = {index}
id = {element.id}
firstName = {element.firstName}
lastName = {element.lastName}
setCategories = {setCategories}
})
)
}
And here's a simplified version of the child component:
const Child = (props) => {
return(
<h1>{props.firstName}</h1>
<input
defaultValue = {props.lastName}
onChange={()=>{
// This is what I need help with.
// I'm a new developer and I don't even know where to start.
// I need this to update the object's lastName property in the parent's array.
}}
)
}
Maybe without knowing it, you have lifted the state: basically, instead of having the state in the Child component, you keep it in the Parent.
This is an used pattern, and there's nothing wrong: you just miss a handle function that allows the children to update the state of the Parent: in order to do that, you need to implement a handleChange on Parent component, and then pass it as props to every Child.
Take a look at this code example:
const Parent = () => {
const [categories, setCategories] = useState([]);
useEffect(() => {
// Making your AXIOS request.
}, []);
const handleChange = (index, property, value) => {
const newCategories = [...categories];
newCategories[index][property] = value;
setCategories(newCategories);
}
return categories.map((c, i) => {
return (
<Child
key={i}
categoryIndex={i}
firstName={c.firstName}
lastName={c.lastName}
handleChange={handleChange} />
);
});
}
const Child = (props) => {
...
const onInputChange = (e) => {
props.handleChange(props.categoryIndex, e.target.name, e.target.value);
}
return (
...
<input name={'firstName'} value={props.firstName} onChange={onInputChange} />
<input name={'lastName'} value={props.lastName} onChange={onInputChange} />
);
}
Few things you may not know:
By using the attribute name for the input, you can use just one handler function for all the input elements. Inside the function, in this case onInputChange, you can retrieve that information using e.target.name;
Notice that I've added an empty array dependecies in your useEffect: without it, the useEffect would have run at EVERY render. I don't think that is what you would like to have.
Instead, I guest you wanted to perform the request only when the component was mount, and that is achievable with n empty array dependecies;
I have a navbar component with that actual info being pulled in from a CMS. Some of the nav links have a dropdown component onclick, while others do not. I'm having a hard time figuring out how to target a specific menus index with React Hooks - currently onClick, it opens ALL the dropdown menus at once instead of the specific one I clicked on.
The prop toggleOpen is being passed down to a styled component based on the handleDropDownClick event handler.
Heres my component.
const NavBar = props => {
const [links, setLinks] = useState(null);
const [notFound, setNotFound] = useState(false);
const [isOpen, setIsOpen] = useState(false);
const fetchLinks = () => {
if (props.prismicCtx) {
// We are using the function to get a document by its uid
const data = props.prismicCtx.api.query([
Prismic.Predicates.at('document.tags', [`${config.source}`]),
Prismic.Predicates.at('document.type', 'navbar'),
]);
data.then(res => {
const navlinks = res.results[0].data.nav;
setLinks(navlinks);
});
}
return null;
};
const checkForLinks = () => {
if (props.prismicCtx) {
fetchLinks(props);
} else {
setNotFound(true);
}
};
useEffect(() => {
checkForLinks();
});
const handleDropdownClick = e => {
e.preventDefault();
setIsOpen(!isOpen);
};
if (links) {
const linkname = links.map(item => {
// Check to see if NavItem contains Dropdown Children
return item.items.length > 1 ? (
<Fragment>
<StyledNavBar.NavLink onClick={handleDropdownClick} href={item.primary.link.url}>
{item.primary.label[0].text}
</StyledNavBar.NavLink>
<Dropdown toggleOpen={isOpen}>
{item.items.map(subitem => {
return (
<StyledNavBar.NavLink href={subitem.sub_nav_link.url}>
<span>{subitem.sub_nav_link_label[0].text}</span>
</StyledNavBar.NavLink>
);
})}
</Dropdown>
</Fragment>
) : (
<StyledNavBar.NavLink href={item.primary.link.url}>
{item.primary.label[0].text}
</StyledNavBar.NavLink>
);
});
// Render
return (
<StyledNavBar>
<StyledNavBar.NavContainer wide>
<StyledNavBar.NavWrapper row center>
<Logo />
{linkname}
</StyledNavBar.NavWrapper>
</StyledNavBar.NavContainer>
</StyledNavBar>
);
}
if (notFound) {
return <NotFound />;
}
return <h2>Loading Nav</h2>;
};
export default NavBar;
Your problem is that your state only handles a boolean (is open or not), but you actually need multiple booleans (one "is open or not" for each menu item). You could try something like this:
const [isOpen, setIsOpen] = useState({});
const handleDropdownClick = e => {
e.preventDefault();
const currentID = e.currentTarget.id;
const newIsOpenState = isOpen[id] = !isOpen[id];
setIsOpen(newIsOpenState);
};
And finally in your HTML:
const linkname = links.map((item, index) => {
// Check to see if NavItem contains Dropdown Children
return item.items.length > 1 ? (
<Fragment>
<StyledNavBar.NavLink id={index} onClick={handleDropdownClick} href={item.primary.link.url}>
{item.primary.label[0].text}
</StyledNavBar.NavLink>
<Dropdown toggleOpen={isOpen[index]}>
// ... rest of your component
Note the new index variable in the .map function, which is used to identify which menu item you are clicking.
UPDATE:
One point that I was missing was the initialization, as mention in the other answer by #MattYao. Inside your load data, do this:
data.then(res => {
const navlinks = res.results[0].data.nav;
setLinks(navlinks);
setIsOpen(navlinks.map((link, index) => {index: false}));
});
Not related to your question, but you may want to consider skipping effects and including a key to your .map
I can see the first two useState hooks are working as expected. The problem is your 3rd useState() hook.
The issue is pretty obvious that you are referring the same state variable isOpen by a list of elements so they all have the same state. To fix the problems, I suggest the following way:
Instead of having one value of isOpen, you will need to initialise the state with an array or Map so you can refer each individual one:
const initialOpenState = [] // or using ES6 Map - new Map([]);
In your fetchLink function callback, initialise your isOpen state array values to be false. So you can put it here:
data.then(res => {
const navlinks = res.results[0].data.nav;
setLinks(navlinks);
// init your isOpen state here
navlinks.forEach(link => isOpen.push({ linkId: link.id, value: false })) //I suppose you can get an id or similar identifers
});
In your handleClick function, you have to target the link object and set it to true, instead of setting everything to true. You might need to use .find() to locate the link you are clicking:
handleClick = e => {
const currentOpenState = state;
const clickedLink = e.target.value // use your own identifier
currentOpenState[clickedLink].value = !currentOpenState[clickedLink].value;
setIsOpen(currentOpenState);
}
Update your component so the correct isOpen state is used:
<Dropdown toggleOpen={isOpen[item].value}> // replace this value
{item.items.map(subitem => {
return (
<StyledNavBar.NavLink href={subitem.sub_nav_link.url}>
<span>{subitem.sub_nav_link_label[0].text}</span>
</StyledNavBar.NavLink>
);
})}
</Dropdown>
The above code may not work for you if you just copy & paste. But it should give you an idea how things should work together.