React Hook to display all boxes checked on a form - reactjs

I've created a form and am saving the data to a json file locally. I can save all the data except for the questions with multiple selections and multiple checkboxes. It only saves the last one selected. I am trying to write a switch statement within a React Hook that is working to help save the submitted form. I keep getting an error "cannot identify type of undefined." I'm new to react and don't know what to do from here.
This is in my hooks folder:
export const useInputChange = (customValue, callback) => {
const [value, setValue] = useState(customValue ? customValue : "" || []);
const handleChange = (event) => {
var newValue;
switch (customValue.type) {
case "multipleSelection":
newValue = $("multipleSelection").find("option:checked");
break;
case "checkboxChoice":
newValue = $("checkboxChoice").find("input:checked");
break;
default:
newValue = event.target.value;
}
setValue(newValue);
if (callback) {
callback(event.target.name, newValue);
}
};
return {
value: value,
handleChange: handleChange
};
};
This is my callback in my components folder:
const callback = (name, value) => {
console.log("callback", name, value);
inlineData[name] = value;
setInlineData(inlineData);
console.log(inlineData);
};
The jquery works in the console to pull up the correct arrays.
This is the component:
export const Survey = (props) => {
const [page, setPage] = useState(1);
const [isFinalPage, setIsFinalPage] = useState(false);
const [surveyValues, setSurveyValues] = useState({});
const [loadedInputs, setLoadedInputs] = useState({});
const [question, setQuestion] = useState({});
const [inlineData, setInlineData] = useState({});
const { surveyId } = props;
const triggerBackendUpdate = () => {
console.log(question);
console.log(surveyValues);
setPage(1);
setSurveyValues({});
setQuestion({});
};
useEffect(() => {
if (surveyId) {
const inputDataFile = import(`./data_${surveyId}.json`);
inputDataFile.then((response) => {
setLoadedInputs(response.default);
});
}
});
const handleSubmit = (event) => {
event.preventDefault();
event.persist();
for (let formInput of event.target.elements) {
const isText = isTextInput(formInput.type);
console.log(formInput);
if (isText) {
surveyValues[formInput.name] = formInput.value;
question[formInput.question] = formInput.question;
}
if (formInput.type === "selectMultiple") {
let selected = [].filter.call(
formInput.options,
(option) => option.selected
);
console.log(formInput);
console.log(selected);
console.log(formInput.options.selected);
const values = selected.map((option) => option.value);
surveyValues[formInput.name] = values;
question[formInput.name] = formInput.question;
}
if (formInput.type === "checkbox") {
surveyValues[formInput.name] = formInput.value;
question[formInput.name] = formInput.question;
}
}
setQuestion(question);
setSurveyValues(surveyValues);
const nextPage = page + 1;
const inputs = props.inputs
? props.inputs.filter((inputOption) => inputOption.page ===
nextPage): [];
if (isFinalPage) {
triggerBackendUpdate();
} else {
if (inputs.length === 0) {
setIsFinalPage(true);
} else {
setPage(nextPage);
}
}
};
const callback = (name, value) => {
console.log("callback", name, value);
inlineData[name] = value;
setInlineData(inlineData);
console.log(inlineData);
};
const saveSurvey = async () => {
await fetch("/api/survey", {
method: "POST",
body: JSON.stringify(inlineData),
headers: {
"Content-Type": "application/json",
},
}).catch((error) => {
console.error(error);
});
};
const inputs = props.inputs
? props.inputs.filter((inputOption) => inputOption.page === page)
: [];
return (
<form onSubmit={handleSubmit}>
{isFinalPage !== true &&
inputs.map((obj, index) => {
let inputKey = `input-${index}-${page}`;
return obj.type === "radio" || obj.type === "checkbox" ? (
<SurveyRadioInput
object={obj}
type={obj.type}
required={props.required}
triggerCallback={callback}
question={obj.question}
defaultValue={obj.defaultValue}
name={obj.name}
key={inputKey}
/>
) : obj.type === "checkbox" ? (
<SurveyCheckboxInput
object={obj}
type={obj.type}
required={props.required}
triggerCallback={callback}
question={obj.question}
defaultValue={obj.defaultValue}
name={obj.name}
key={inputKey}
/>
) : obj.type === "select" ? (
<SurveySelectInput
className="form-control mb-3 mt-3"
object={obj}
type={obj.type}
question={obj.question}
required={props.required}
triggerCallback={callback}
defaultValue={obj.defaultValue}
name={obj.name}
key={inputKey}
/>
) : obj.type === "selectMultiple" ? (
<SurveySelectMultipleInput
className="form-control mb-3 mt-3"
object={obj}
type={obj.type}
question={obj.question}
required={props.required}
triggerCallback={callback}
defaultValue={obj.defaultValue}
name={obj.name}
key={inputKey}
/>
) : (
<SurveyTextInput
className="mb-3 mt-3 form-control"
object={obj}
type={obj.type}
question={props.question}
required={props.required}
triggerCallback={callback}
placeholder={obj.placeholder}
defaultValue={obj.defaultValue}
name={obj.name}
key={inputKey}
/>
);
})}
{isFinalPage !== true ? (
<button name="continue-btn" className="btn btn-primary my-5 mx-5">
Continue
</button>
) : (
<Link to="/thankyou">
<button
onClick={saveSurvey}
type="button"
className="btn btn-primary my-5 mx-5"
>
Submit Survey
</button>
</Link>
)}
</form>
);
};
This is in my inputs folder:
export const SurveySelectMultipleInput = (props) => {
const { object } = props;
const { value, handleChange } = useInputChange(
props.defaultValue,
props.triggerCallback
);
const inputType = isTextInput(props.type) ? props.type : "";
const inputProps = {
className: props.className ? props.className : "form-control",
onChange: handleChange,
value: value,
required: props.required,
question: props.question,
type: inputType,
name: props.name ? props.name : `${inputType}_${props.key}`,
};
console.log(value);
return (
<>
<div id={object.name}>
<h5>{props.question}</h5>
<select
{...inputProps}
name={object.name}
className={props.className}
multiple={object.multiple}
>
<option hidden value>
Select one
</option>
{object.options.map((data, index) => {
return (
<option
value={data.value}
id={`${object.name}-${index}`}
key={`${object.type}-${index}`}
className={`form-check ${props.optionClassName}`}
>
{data.label}
</option>
);
})}
</select>
</div>
</>
);
};

It's hard to tell exactly how your components and hooks behave without having an example showing their behavior and properties. Regardless, I made some assumptions and tried to answer:
First of all, what is the expected type of customValue in useInputChange? Are you expecting a string or an array? Then what is the type attribute on it that you're checking in your switch statement?
As for the jquery selector, what is multipleSelection? Is it the class name you're using for your select elements? Then your selector must start with a dot a/nd then you can get the value by calling .val method on the selected element:
newValue = $(".multipleSelection").val();
Here's a working example for multiple select elements, using your code: https://codepen.io/kaveh/pen/QWNNQMV
Note that I had to assign an arbitrary type attribute to VALUE to get it working with your switch statement.
All that being said, as I mentioned in my comment, it's recommended to use ref to access elements created by React and not other query selectors such as those you get from jquery.
https://reactjs.org/docs/refs-and-the-dom.html
https://reactjs.org/docs/hooks-reference.html#useref

Related

how to update input defaultvalue using useRef (after the initial render?)

const Component = ()=>{
const [list, setList] = useState(getLocalStorage());
const [isEditing, setIsEditing] = useState(false);
const [itemToEdit, setItemToEdit] = useState();
const refContainer = useRef(null);
const putLocalStorage = () => {
localStorage.setItem("list", JSON.stringify(list));
};
const editItem = (id) => {
refContainer.current.focus();
setItemToEdit(() => {
return list.find((item) => item.id === id);
});
setIsEditing(true);
};
const handleSubmit = (e)=>{
e.preventDefault();
let nameValue = refContainer.current.value;
if (isEditing){
setList(list.map((item)=>{
if (item.id === itemToEdit.id){
return {...item, name: nameValue};
}
else {
return item;
}
);
}
else {
let newItem = {
id: new Date().getItem().toString(),
name: nameValue,
}
setList([...list, newItem])
}
nameValue="";
setIsEditing(false);
}
useEffect(() => {
putLocalStorage();
}, [list]);
return (
<div>
<form onSubmit={handleSubmit}>
<input type="text" ref={refContainer} defaultValue={isEditing ? itemToEdit.name : ""}/>
<button type="submit">submit</button>
</form>
<div>
{list.map((item) => {
const { id, name } = item;
return (
<div>
<h2>{name}</h2>
<button onClick={() => editItem(id)}>edit</button>
<button onClick={() => deleteItem(id)}>
delete
</button>
</div>
);
})}
</div>
</div>
)
}
So this part:
<input type="text" ref={refContainer} defaultValue={isEditing ? itemToEdit.name : ""} />
I want to show to users what they are editing by displaying the itemToEdit on the input.
It works on the first time when the user clicks edit button
But after that, the defaultValue does not change to itemToEdit
Do you guys have any idea for the solution?
(i could use controlled input instead, but i want to try it with useRef only)
Otherwise, placeholder will be the only solution...
The defaultValue property only works for inicial rendering, that is the reason that your desired behavior works one time and then stops. See a similar question here: React input defaultValue doesn't update with state
One possible solution still using refs is to set the itemToEdit name directly into the input value using ref.current.value.
const editItem = (id) => {
refContainer.current.focus();
setItemToEdit(() => {
const item = list.find((item) => item.id === id);
refContainer.current.value = item.name;
return item;
});
setIsEditing(true);
};

How can I filter array while typing

Like with my solution, I have to type "Back-End Developer" to get filter results. Can I just show results while typing "back" or "backend"? Even if I don't type the "-" filter doesn't work.
I guess I have to use some and toLowerCase but I don't know where to use it.
const Positions = ({ positions }: DataProps) => {
const [selectLocation, setSelectLocation] = useState<any>('');
const [selectJobType, setSelectJobType] = useState<any>('');
const [filtered, setFiltered] = useState<any[]>([]);
const [searchTerm, setSearchTerm] = useState<any>('');
useEffect(() => {
if (positions.length > 0) {
let newList = [...positions];
if (searchTerm) {
newList = newList.filter((i) => i.position === searchTerm);
}
if (selectJobType) {
newList = newList.filter((i) => i.position === selectJobType);
}
if (selectLocation) {
newList = newList.filter((i) => i.location === selectLocation);
}
setFiltered(newList);
}
}, [positions, searchTerm, selectJobType, selectLocation]);
return (
<>
<div>
<input
type='search'
placeholder='Search'
onChange={(e) => setSearchTerm(e.target.value)}
/>
<Select
defaultValue={selectLocation}
onChange={setSelectLocation}
options={locations}
instanceId={'1'}
placeholder='Location'
/>
</div>
<Select
defaultValue={selectJobType}
onChange={setSelectJobType}
options={jobs}
placeholder='Job Type'
instanceId={'2'}
/>
{positions?.map((position: any) => (
<SinglePosition
category={position.category}
type={position.type}
location={position.location}
position={position.position}
key={position._id}
/>
))}
</>
);
};
Do not need to use the === operator just use the includes method
useEffect(() => {
if(positions.length > 0) {
let newList = [...positions];
if(searchTerm) {
newList = newList.filter(i => i.position.toLowerCase().includes(searchTerm.toLowerCase()));
}
if(selectJobType) {
newList = newList.filter(i => i.position.toLowerCase().includes(selectJobType.toLowerCase()));
}
if(selectLocation) {
newList = newList.filter(i => i.location.toLowerCase().includes(selectLocation.toLowerCase()));
}
setFiltered(newList);
}
}, [positions, searchTerm, selectJobType, selectLocation]);

REACT-Send requests the selected dish options ids to my backend not working

How can I retrieve the dishId selected from my options react - select that shows me thedishType in order to send them my parent component FormRender and to the backend.
My first dropdown shows me: Menu1, Menu2...
My second one: type2...
So if I click ontype4, how can I store the related dishId(here = 4). I can click on several values i.e: type2 andtype3.
How do I keep the dish ids i.e : 2 and 3 and send them to my FormRender parent
Menus(first page of my multi - step form):
export default function Menus() {
const [selectionMenus, setSelectionMenus] = useState({});
const [selectionDishes, setSelectionDishes] = useState({});
const [menus, setMenus] = useState([])
const [date, setDate] = useState('')
useEffect(() => {
axios
.post(url)
.then((res) => {
console.log(res);
setMenus(res.data.menus);
})
.catch((err) => {
console.log(err);
});
}, []);
const names = menus?.map(item => {
return {
label: item.menuId,
value: item.name
}
})
const types = menus?.flatMap(item => {
return item.dishes.map(d => ({
label: d.dishId,
value: d.dishType
}))
})
const handle = (e) => {
if (e?.target?.id === undefined) return setInfo(e);
if (e?.target?.id === undefined) return setSelectionMenus(e);
if (e?.target?.id === undefined) return setSelectionDishes(e);
switch (e.target.id) {
case "date":
setDate(e.target.value);
break;
...
default:
}
}
};
return (
<>
<form>
<div>My menus</div>
<label>
Dishes :
<Dropdown
options={names}
value={selectionMenus}
setValue={setSelectionMenus}
isMulti={true}
/>
</label>
<label>
<Dropdown
options={types}
value={selectionDishes}
setValue={setSelectionDishes}
isMulti={true}
/>
</label>
<label>
Date:
<div>
<input
type="date"
name='date'
value={date}
onChange={handle}
id="date"
/>
</div>
</label>
...
</form>
<div>
<button onClick={() => nextPage({ selectionDishes, selectionMenus, date })}>Next</button>
</div>
</>
);
}
Here the parent Component FormRender that is supposed to retrieve the values of all dishId selected and send them to the backend:
export default function FormRender() {
const [currentStep, setCurrentStep] = useState(0);
const [info, setInfo] = useState();
const [user, setUser] = useState();
const headers = ["Menus", "Details", "Final"];
const steps = [
<Menus
nextPage={(menu) => {
setInfo(menu);
setCurrentStep((s) => s + 1);
}}
/>,
<Details
backPage={() => setCurrentStep((s) => s - 1)}
nextPage={setUser}
/>,
<Final />
];
useEffect(() => {
if (info === undefined || user === undefined) return;
const data = {
date: info.date,
id: //list of dishId selected but don't know how to do that??
};
}, [info, user]);
return (
<div>
<div>
<Stepper steps={headers} currentStep={currentStep} />
<div >{steps[currentStep]}</div>
</div>
</div>
);
}
Dropdown:
export default function Dropdown({ value, setValue, style, options, styleSelect, isMulti = false }) {
function change(option) {
setValue(option.value);
}
return (
<div onClick={(e) => e.preventDefault()}>
{value && isMulti === false ? (
<Tag
selected={value}
setSelected={setValue}
styleSelect={styleSelect}
/>
) : (
<Select
value={value}
onChange={change}
options={options}
isMulti={isMulti}
/>
)}
</div>
);
}
Here my json from my api:
{
"menus": [
{
"menuId": 1,
"name": "Menu1",
"Description": "Descritption1",
"dishes": [
{
"dishId": 2,
"dishType": "type2"
},
{
"dishId": 3,
"dishType": "type3"
},
{
"dishId": 4,
"dishType": "type4"
}
]
},
...
]
}
You already store the selected values inside the selectionMenus and selectionDishes states. So, if you want to send them to the parent FormRender component you can instead create those two states inside that component like this:
export default function FormRender() {
const [selectionMenus, setSelectionMenus] = useState();
const [selectionDishes, setSelectionDishes] = useState();
....
}
Then pass those values to the Menus component:
<Menus
selectionMenus={selectionMenus}
setSelectionMenus={setSelectionMenus}
selectionDishes={selectionDishes}
setSelectionDishes={setSelectionDishes}
nextPage={(menu) => {
setInfo(menu);
setCurrentStep((s) => s + 1);
}}
/>
Subsequently, you will have to remove the state from the Menus component and use the one you receive from props:
export default function Menus({ selectionMenus, setSelectionMenus, selectionDishes, setSelectionDishes }) {
/*const [selectionMenus, setSelectionMenus] = useState({}); //remove this line
const [selectionDishes, setSelectionDishes] = useState({});*/ //remove this line
...
}
Finally, you can use inside your useEffect hook the two states and map them to only get the selected ids:
useEffect(() => {
// ... other logic you had
if(selectionDishes?.length && selectionMenus?.length){
const data = {
date: info.date,
id: selectionDishes.map(d => d.dishId),
idMenus: selectionMenus.map(m => m.menuId)
};
}
}, [info, user, selectionMenus, selectionDishes]);
react-select has options to format the component:
getOptionLabel: option => string => used to format the label or how to present the options in the UI,
getOptionValue: option => any => used to tell the component what's the actual value of each option, here you can return just the id
isOptionSelected: option => boolean => used to know what option is currently selected
onChange: option => void => do whatever you want after the input state has changed
value => any => if you customize the above functions you may want to handle manually the value
Hope it helps you

Text field should only change for one value and not over the entire list

I have a list and this list has several elements and I iterate over the list. For each list I display two buttons and an input field.
Now I have the following problem: as soon as I write something in a text field, the same value is also entered in the other text fields. However, I only want to change a value in one text field, so the others should not receive this value.
How can I make it so that one text field is for one element and when I write something in this text field, it is not for all the other elements as well?
import React, { useState, useEffect } from 'react'
import axios from 'axios'
function Training({ teamid }) {
const [isTrainingExisting, setIsTrainingExisting] = useState(false);
const [trainingData, setTrainingData] = useState([]);
const [addTraining, setAddTraining] = useState(false);
const [day, setDay] = useState('');
const [from, setFrom] = useState('');
const [until, setUntil] = useState('');
const getTrainingData = () => {
axios
.get(`${process.env.REACT_APP_API_URL}/team/team_training-${teamid}`,
)
.then((res) => {
if (res.status === 200) {
if (typeof res.data !== 'undefined' && res.data.length > 0) {
// the array is defined and has at least one element
setIsTrainingExisting(true)
setTrainingData(res.data)
}
else {
setIsTrainingExisting(false)
}
}
})
.catch((error) => {
//console.log(error);
});
}
useEffect(() => {
getTrainingData();
}, []);
const deleteTraining = (id) => {
axios
.delete(`${process.env.REACT_APP_API_URL}/team/delete/team_training-${teamid}`,
{ data: { trainingsid: `${id}` } })
.then((res) => {
if (res.status === 200) {
var myArray = trainingData.filter(function (obj) {
return obj.trainingsid !== id;
});
//console.log(myArray)
setTrainingData(() => [...myArray]);
}
})
.catch((error) => {
console.log(error);
});
}
const addNewTraining = () => {
setAddTraining(true);
}
const addTrainingNew = () => {
axios
.post(`${process.env.REACT_APP_API_URL}/team/add/team_training-${teamid}`,
{ von: `${from}`, bis: `${until}`, tag: `${day}` })
.then((res) => {
if (res.status === 200) {
setAddTraining(false)
const newTraining = {
trainingsid: res.data,
mannschaftsid: teamid,
von: `${from}`,
bis: `${until}`,
tag: `${day}`
}
setTrainingData(() => [...trainingData, newTraining]);
//console.log(trainingData)
}
})
.catch((error) => {
console.log(error);
});
}
const [editing, setEditing] = useState(null);
const editingTraining = (id) => {
//console.log(id)
setEditing(id);
};
const updateTraining = (trainingsid) => {
}
return (
<div>
{trainingData.map((d, i) => (
<div key={i}>
Trainingszeiten
<input class="input is-normal" type="text" key={ d.trainingsid } value={day} placeholder="Wochentag" onChange={event => setDay(event.target.value)} readOnly={false}></input>
{d.tag} - {d.von} bis {d.bis} Uhr
<button className="button is-danger" onClick={() => deleteTraining(d.trainingsid)}>Löschen</button>
{editing === d.trainingsid ? (
<button className="button is-success" onClick={() => { editingTraining(null); updateTraining(d.trainingsid); }}>Save</button>
) : (
<button className="button is-info" onClick={() => editingTraining(d.trainingsid)}>Edit</button>
)}
<br />
</div>
))}
)
}
export default Training
The reason you see all fields changing is because when you build the input elements while using .map you are probably assigning the same onChange event and using the same state value to provide the value for the input element.
You should correctly manage this information and isolate the elements from their handlers. There are several ways to efficiently manage this with help of either useReducer or some other paradigm of your choice. I will provide a simple example showing the issue vs no issue with a controlled approach,
This is what I suspect you are doing, and this will show the issue. AS you can see, here I use the val to set the value of <input/> and that happens repeatedly for both the items for which we are building the elements,
const dataSource = [{id: '1', value: 'val1'}, {id: '2', value: 'val2'}]
export default function App() {
const [val, setVal]= useState('');
const onTextChange = (event) => {
setVal(event.target.value);
}
return (
<div className="App">
{dataSource.map(x => {
return (
<div key={x.id}>
<input type="text" value={val} onChange={onTextChange}/>
</div>
)
})}
</div>
);
}
This is how you would go about it.
export default function App() {
const [data, setData]= useState(dataSource);
const onTextChange = (event) => {
const id = String(event.target.dataset.id);
const val = String(event.target.value);
const match = data.find(x => x.id === id);
const updatedItem = {...match, value: val};
if(match && val){
const updatedArrayData = [...data.filter(x => x.id !== id), updatedItem];
const sortedData = updatedArrayData.sort((a, b) => Number(a.id) - Number(b.id));
console.log(sortedData);
setData(sortedData); // sorting to retain order of elements or else they will jump around
}
}
return (
<div className="App">
{data.map(x => {
return (
<div key={x.id}>
<input data-id={x.id} type="text" value={x.value} onChange={onTextChange}/>
</div>
)
})}
</div>
);
}
What im doing here is, finding a way to map an element to its own with the help of an identifier. I have used the data-id attribute for it. I use this value again in the callback to identify the match, update it correctly and update the state again so the re render shows correct values.

How to update an array of state using useEffect

I want to get latest state after updating state.
So I need to use useEffect.
After I change content of todo, I call saveEditedTodo onBlur.
So my code is,
useEffect(() => {
console.log(todos)
// I need to setTodos(todos), but it causes infinite loop
}, [todos]);
const saveEditedTodo = (e, id) => {
const newContent = e.currentTarget.innerHTML;
const editedTodo = todos.map((todo) =>
todo.id === id ? { ...todo, todoItem: newContent } : todo,
);
setTodos(editedTodo); // Re-rendering
onBlur(todos); // Re-rendering
};
And onBlur from props is,
const handleOnBlurTodo = (value) => {
const newValue = convertTodoToNote(value);
setEditableNote({ ...editableNote, content: newValue });
};
How can I get latest state using useEffect?
(+) Here is my full code!
function TodoList({ todoContent, onBlur }) {
const [todos, setTodos] = useState(todoContent);
const [isHover, setIsHover] = useState({ hoverID: '', onHover: false });
const { hoverID, onHover } = isHover;
const isEditable = useSelector((state) => state.isSelected);
const doneTodo = todos ? todos.filter((todo) => todo.isDone).length : 0;
useEffect(() => {
console.log(todos);
}, [todos]);
const saveEditedTodo = (e, id) => {
const newContent = e.currentTarget.innerHTML;
const editedTodo = todos.map((todo) =>
todo.id === id ? { ...todo, todoItem: newContent } : todo,
);
setTodos(editedTodo); // Re-rendering
onBlur(todos); // Re-rendering
};
const handleDeleteTodo = (id) => {
let newTodos = todos.filter((el) => el.id !== id);
setTodos(newTodos);
onBlur(todos);
};
const handleOnMouseOver = (id) => {
setIsHover({ hoverID: id, onHover: true });
};
const handleOnMouseLeave = (id) => {
setIsHover({ hoverID: id, onHover: false });
};
const handleCheckbox = (id) => {
const newTodos = todos.map((todo) =>
todo.id === id ? { ...todo, isDone: !todo.isDone } : todo,
);
setTodos(newTodos);
console.log('[todos]' + todos);
};
const todoTask = todos.filter((todo) => !todo.isDone);
const doneTask = todos.filter((todo) => todo.isDone);
if (isEditable && todos) {
let todoList = todoTask.map((todo, i) => (
<TodoListContainer
key={i}
onMouseEnter={() => handleOnMouseOver(todo.id)}
onMouseLeave={() => handleOnMouseLeave(todo.id)}
>
<Checkbox
type="checkbox"
checked={todo.isDone}
onChange={() => handleCheckbox(todo.id)}
/>
<NoteTitle
isTodoItem
size="medium"
placeholder="Add Todo"
onBlur={(e) => saveEditedTodo(e, todo.id)}
contentEditable
suppressContentEditableWarning="true"
>
{todo.todoItem}
</NoteTitle>
{hoverID === todo.id && onHover && (
<Tool
title="Delete Todo"
bgImage={DeleteIcon}
deleteTodo={() => handleDeleteTodo(todo.id)}
/>
)}
</TodoListContainer>
));
let doneList = doneTask.map((todo, i) => (
<TodoListContainer
key={i}
onMouseEnter={() => handleOnMouseOver(todo.id)}
onMouseLeave={() => handleOnMouseLeave(todo.id)}
>
<Checkbox
type="checkbox"
onBlur={() => handleCheckbox(todo.id)}
checked={todo.isDone}
/>
<NoteTitle
isTodoItem
size="medium"
placeholder="Add Todo"
onInput={(e) => saveEditedTodo(e, todo.id)}
contentEditable
suppressContentEditableWarning="true"
>
{todo.todoItem}
</NoteTitle>
{hoverID === todo.id && onHover && (
<Tool
title="Delete Todo"
bgImage={DeleteIcon}
deleteTodo={() => handleDeleteTodo(todo.id)}
/>
)}
</TodoListContainer>
));
return (todoList = (
<div>
{todoList}
{doneTodo > 0 && <CompletedTodo doneTodo={doneTodo} />}
{doneList}
</div>
));
}
if (!isEditable && todos) {
const todoList = todos.map((todo, i) => (
<TodoListContainer key={i}>
<Checkbox
type="checkbox"
onChange={() => handleCheckbox(todo.id)}
checked={todo.isDone}
/>
<NoteTitle size="small">{todo.todoItem}</NoteTitle>
</TodoListContainer>
));
return todoList;
}
return null;
}
export default TodoList;
Generally React.useEffect() is used for performing side effects for a React component. What I believe is that you wish to get the new state rendered on screen after saving the TODO content, and that can be just achieved by an onChange handler wherever you are receiving the input for your todos.
<TextField onChange={(e) => saveEditedTodos(e, id)} />
This will trigger the saveEditedTodos callback every time the value of the TextField changes. If you want to trigger the callback on clicking a save button, you can add an onClick handler in the Button component.
Another scenario what I can imagine is that you're saving your TODOs somewhere, so you want to update the list on the screen after saving the TODO in some storage, in that case you can fetch the value of todoList on each save. This can be done inside a useEffect hook callback.
React.useEffect(() => {
fetchTodos().then((response) => setTodos(response.data))
})
Here fetchTodos() is a JS Promise or async function which fetches the updated state of TODOs and sets the received data using setTodos

Resources