Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
sample for friend
import React, { useState, useEffect, useMemo, useCallback } from 'react';
const Student = ({ id, name, onChange }) => {
const handleOnChange = useCallback((event) => {
if (typeof onChange === 'function') {
onChange(id, event.target.value);
}
}, [id, onChange]);
return (
<input type="text" value={name} onChange={handleOnChange} />
);
};
const Students = () => {
const [students, setStudents] = useState([]);
useEffect(() => {
fetch("..").then((reponse) => {
setStudents(response.data.map((item) => {
return {
id: item.id,
name: item.firstName,
}
}));
})
}, [setStudents]);
const handleStudentNameChange = useCallback((id, name) => {
fetch('..').then((response) => {
setStudents((state) => {
const item = state.find((i) => (i.id === response.data.id));
item.name = response.data.firstName;
return [...state];
});
});
}, [setStudents]);
const children = useMemo(() => (
students.map((item) => (
<Student key={item.id} id={item.id} name={item.name} onChange={handleStudentNameChange} />
))
), [students]);
return (
<div>
{children}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment