Implementing real time filtering/search with Django and React not working as expected

44 Views Asked by At

I'm trying to implement real time filtering/search with Django and React. But I'm not getting desired results? Please what did I do wrong?

Here is my views.py file:

class FilterFormView(generics.ListAPIView):
    serializer_class = JournalSerializer
   
    def get_queryset(self):
        qs = Journal.objects.all()
        title_contains_query = self.request.query_params.get("title_contains")
        if is_valid_query_param(title_contains_query):
            qs = qs.filter(title__icontains=title_contains_query)
        return qs

The filtering Form in React looks like this:

 useEffect(() => {
    fetchJournals();
  }, [title_contains]);
  const fetchJournals = async () => {
    setLoading(true);
    try {
      const res = await axios.get(myurl);
      setPost(res.data);
      setLoading(false);
    } catch (e) {
      console.log(e);
    }
  };
 const handleChange = (e) => {
    settitle_contains({
      ...title_contains,
      [e.target.name]: e.target.value,
    });
  };
return (
    <React.Fragment>
      <input
        onChange={handleChange}
        type="text"
        name="title_contains"
        id="title_contains"
      />

      {post.map((jour) => {
        return <div>{jour.title}</div>;
      })}
      {loading && <div>Data is Loading</div>}
    </React.Fragment>
  );

This was how I set my url:

const [title_contains, settitle_contains] = useState("");
const url = new URL("http://127.0.0.1:8000/api/?");
url.searchParams.set("title_contains", title_contains);

I got this from the server console whenever I typed in the input field and no filtering occured in the frontend:

[08/Jul/2023 19:40:38] "GET /api/?title_contains=%5Bobject+Object%5D HTTP/1.1" 200 2

But if url is set like this:

const myurl = http://127.0.0.1:8000/api/?${title_contains};

Then I got this from the server console each time I type in the input field and no filtering occured in the frontend:

[08/Jul/2023 19:40:54] "GET /api/?[object%20Object] HTTP/1.1" 200 42551

I expect to see something like this instead:

[08/Jul/2023 19:54:17] "GET /api/?title_contains=Music HTTP/1.1" 200 2689

0

There are 0 best solutions below