fix: conflicting fetch with /api/convos

This commit is contained in:
Daniel Avila 2023-03-18 14:28:10 -04:00
parent 0f54ffd8b4
commit b97594c000
10 changed files with 199 additions and 90 deletions

View file

@ -1,18 +1,34 @@
import React, { useState, useCallback } from 'react';
import { debounce } from 'lodash';
import { useDispatch, useSelector } from 'react-redux';
import { useDispatch } from 'react-redux';
import { Search } from 'lucide-react';
import { setQuery } from '~/store/searchSlice';
import { setPage, refreshConversation } from '~/store/convoSlice';
import { setConvos, refreshConversation } from '~/store/convoSlice';
import axios from 'axios';
export default function SearchBar() {
const fetch = async (q, pageNumber, callback) => {
const { data } = await axios.get(`/api/search?q=${q}&pageNumber=${pageNumber}`);
console.log(data);
callback(data);
};
export default function SearchBar({ onSuccess, clearSearch }) {
const dispatch = useDispatch();
const [inputValue, setInputValue] = useState('');
const { search } = useSelector((state) => state.search);
// const onSuccess = (data) => {
// const { conversations, pages, pageNumber } = data;
// dispatch(setConvos({ convos: conversations, searchFetch: true }));
// dispatch(setPage(pageNumber));
// dispatch(setPages(pages));
// };
const debouncedChangeHandler = useCallback(
debounce((q) => {
dispatch(setQuery(q));
if (q.length > 0) {
fetch(q, 1, onSuccess);
}
}, 750),
[dispatch]
);
@ -22,27 +38,27 @@ export default function SearchBar() {
if (e.keyCode === 8 && value === '') {
// Value after clearing input: ""
console.log(`Value after clearing input: "${value}"`);
dispatch(setPage(1));
dispatch(setQuery(''));
dispatch(refreshConversation());
clearSearch();
}
};
const changeHandler = (e) => {
if (!search) {
console.log('setting page to 1');
dispatch(setPage(1));
}
// if (!search) {
// console.log('setting page to 1');
// dispatch(setPage(1));
// }
let q = e.target.value;
setInputValue(q);
q = q.trim();
if (q === '' || !q) {
dispatch(setPage(1));
if (q === '') {
dispatch(setQuery(''));
dispatch(refreshConversation());
// dispatch(setPage(1));
// dispatch(refreshConversation());
clearSearch();
} else {
debouncedChangeHandler(q);
}