search bar causing infinite loop in React
Here's parent component:
const Page = () => {
const { user } = useAuth();
const router = useRouter();
const [allUsers, setAllUsers] = useState([]);
const [search, useSearch] = useState("");
useEffect(
() => {
if (user !== null && user.isAdmin) {
const token = localStorage.getItem("token");
api
.get("/users", {
headers: {
authorization: `Bearer ${token}`,
},
})
.then((data) => {
setAllUsers(data.data);
})
.catch((error) => {
if (error.message === "Request failed with status code 401") {
const refresh_token = localStorage.getItem("refresh_token");
const refresh = api
.post("/auth/refresh", {
refresh_token,
})
.then((req) => {
if (refresh.data.token && refresh.data.refresh_token) {
localStorage.setItem("token", refresh.data.token);
localStorage.setItem(
"refresh_token",
refresh.data.refresh_token
);
api
.get("/users", {
headers: {
authorization: `Bearer ${refresh.data.token}`,
},
})
.then((req) => {
setAllUsers(req.data);
});
}
})
.catch((error) => {
if (error.message === "Request failed with status code 400") {
if (error.response.data.message
=== "Refresh Token não encontrado."
) {
router.push("/");
}
}
});
}
});
} else if (!user) {
router.push("/404");
} else {
router.push("/auth/login");
}
},
[user, router]
);
useEffect(
() => {
const filterSearch = () => {
if (search === "") return allUsers;
return allUsers.filter((user) => user._id.includes(search));
};
const filtered = filterSearch(search);
setAllUsers(filtered);
},
[search, allUsers],
search
);
const useConsultasPagination = (data, page, rowsPerPage) => {
return useMemo(() => {
return applyPagination(data, page, rowsPerPage);
}, [data, page, rowsPerPage]);
};
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(5);
const keys = useConsultasPagination(allUsers, page, rowsPerPage);
const handlePageChange = useCallback((event, value) => {
setPage(value);
}, []);
const handleRowsPerPageChange = useCallback((event) => {
setRowsPerPage(event.target.value);
}, []);
if (user !== null && user.isAdmin) {
return (
Search | API
Users
);
} else {
router.push("/404");
}
}
And here's search bar's component:
export const UsersSearch = (props) => {
const {
setAllUsers = () => {},
allUsers = [],
search = "",
useSearch = () => {}
} = props;
const { user } = useAuth();
const router = useRouter();
const SetSearch = (value) => {
useSearch(value);
};
const HandleInputChange = (event) => {
console.log('a')
event.preventDefault();
const target = event.target;
const value = target.value;
if (value === "") {
SetSearch("")
} else {
SetSearch(value);
}
};
if (user.isAdmin) {
return (
);
} else {
router.push("/404");
}
};
The problem I'm facing is that, everytime a change the text in the search I get an infinite loop, although the search feature works (and when I remove all the text from the bar it doesn't comes back to the initial allUsers value).
Help me please :)
Changed the useEffect from causing another loop
0 comments:
Post a Comment
Thanks