Search code examples
javascriptreactjsdjangoreact-nativereact-native-paper

How to build a search function in react native app?


I have a react native app. And I have a search function. The problem I am facing is that the search function only works when the whole word has been entered in the textfield.

So for example Edelhert works. But if a user types in: Ed - then nothing happens.

And if a user waits for a second in the search textfield. Then this error pops up:

VM270:1  Uncaught SyntaxError: Unexpected identifier 'Promise'

So the search api looks:

import { API_URL } from "@env";
import { retrieveToken } from "../../services/authentication/token";

export const fetchAnimalData = async (text) => {
    const token = await retrieveToken();
    try {
        if (token) {
            const response = await fetch(`${API_URL}/api/animals/?name=${text}`, {
                method: "GET",
                headers: {
                    Authorization: `Token ${token}`,
                    Accept: "application/json",
                    "Content-Type": "application/json",
                },
            });
            return await response.json();
        } else {
            throw new Error(token);
        }
    } catch (error) {
        console.error("There was a problem with the fetch operation:", error);
        throw error;
    }
};

and the search context:

/* eslint-disable prettier/prettier */

import React, { createContext, useEffect, useState } from "react";
import { fetchAnimalData } from "./animal/animal.service";
export const SearchAnimalContext = createContext();
export const SearchAnimalContextProvider = ({ children }) => {
    const [searchAnimal, setSearchAnimal] = useState([]);
    const [results, setResults] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [input, setInput] = useState("");

    useEffect(() => {
        fetchAnimalData();
    }, [searchAnimal]);

    const performSearch = async (text) => {
        setLoading(true);
        setError(null);
        setTimeout(() => {
            fetchAnimalData(text)
                .then((response2) => {
                    setResults(response2);
                    setLoading(false);
                })
                .catch((err) => {
                    setLoading(false);
                    setError(err);
                });
        });
    };
    return (
        <SearchAnimalContext.Provider
            value={{
                results,
                setResults,
                searchAnimal,
                setSearchAnimal,
                input,
                setInput,
                performSearch,
                loading,
                error,
            }}>
            {children}
        </SearchAnimalContext.Provider>
    );
};

And the component with the searchfield:

import React, { useContext, useState } from "react";

import { AccordionItemsContext } from "../../../services/accordion-items.context";
import { AnimalDetailToggle } from "../../../components/general/animal-detail-toggle-view";
import { CategoryContext } from "../../../services/category/category.context";
import { CategoryInfoCard } from "../components/category-info-card.component";
import { SafeArea } from "../../../components/utility/safe-area.component";
import { SearchAnimalContext } from "../../../services/search-animal.context";
import { Searchbar } from "react-native-paper";

export const CategoryScreen = ({ navigation }) => {
    useContext(AccordionItemsContext);  
    const { loading, categoryList } = useContext(CategoryContext);
    const { performSearch, results, setInput, input } = useContext(SearchAnimalContext);
    const [searchTimer, setSearchTimer] = useState(null);

    return (
        <SafeArea>
            {loading && (
                <LoadingContainer>
                    <ActivityIndicator animating={true} color={MD2Colors.blue500} />
                </LoadingContainer>
            )}
            <Searchbar
                placeholder="search animalll"
                onChangeText={(text) => {
                    if (searchTimer) {
                        clearTimeout(searchTimer);
                    }
                    if (!text.length) {
                        setInput("");
                        return;
                    }

                    setInput(text.substring(0));
                    setSearchTimer(setTimeout(performSearch(text), 1000));
                }}
                value={input}
            />

        </SafeArea>
    );
};

And for the backend I am using django. One of the views is this one:

from django_filters.rest_framework import DjangoFilterBackend
# from WelzijnAdmin.permissions import AdminReadOnly
from rest_framework import permissions, viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django.contrib.auth.decorators import permission_required
from rest_framework import filters

from .models import Animal, Category
from .serializers import (AnimalSerializer, CategorySerializer,
                          MainGroupSerializer)


class AnimalViewSet(viewsets.ModelViewSet, permissions.BasePermission):

    queryset = Animal.objects.all().order_by('name')
    serializer_class = AnimalSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]

    filterset_fields = ['name']
    search_fields = ['name']


class CategoryViewSet(viewsets.ModelViewSet, permissions.BasePermission):
    """
    This API endpoint allows for the viewing of animal categories.

    All categories include their direct subcategories and animals.

    - To view a specific category, append the url with its [/id](/api/categories/1/).
    - To get all top-level categories use [/main_groups](/api/categories/main_groups). 
    """

    def get_serializer_class(self):
        if hasattr(self, 'action') and self.action == 'main_groups':
            return MainGroupSerializer
        return CategorySerializer

    queryset1 = Category.objects.all().order_by('name')
    queryset = CategorySerializer.eager_load(queryset1)
    serializer_class = get_serializer_class(super)

    permission_classes = (IsAuthenticated,)

    @action(methods=['get'], detail=False)
    # @permission_required("category")
    def main_groups(self, request):
        """
        Returns a list of top level Categories.

        - To view a specific category, append the url with its [/id](/api/categories/1/).
        """
        main_groups = Category.objects.filter(category_id__isnull=True)
        serializer = self.get_serializer(main_groups, many=True)

        return Response(serializer.data)

And if I go to

http://127.0.0.1:8000/api/animals/

and then choose for filter and type in the searchfield el, then the animals are filtered who has the letters el in it:

[
    {
        "id": 15,
        "name": "Blauwgele Ara",
       
    },
    {
        "id": 71,
        "name": "Edelhert",

    {
        "id": 19,
        "name": "Edelpapegaai",
}]

or I type in ar:


 {
        "id": 15,
        "name": "Blauwgele Ara",
     
    },
    {
        "id": 24,
        "name": "Bobakmarmot",
}

What I already have done? Of course googled a lot. Watching youtube clips. For example this one:

https://www.youtube.com/watch?v=i1PN_c5DmaI

But I don't see the mistake that prevents partly searching for a word.

Question: how to implement partly searching for a word?


Solution

  • Ah, oke. I didnt knew that. I am also learning. But what I did. In the backend I changed this:

    class AnimalViewSet(viewsets.ModelViewSet, permissions.BasePermission):
    
        queryset = Animal.objects.all().order_by('name')
        serializer_class = AnimalSerializer
        permission_classes = [IsAuthenticated]
        filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    
        filterset_fields = ['name']
        search_fields = ['name']
    
        def get_queryset(self):
            qs = Animal.objects.all()
            name = self.request.query_params.get('name')
            if name is not None:
                qs = qs.filter(name_icontains=name)
            return qs
    

    And in the frontend I changed this:

    export const fetchAnimalData = async (text) => {
        const token = await retrieveToken();
        try {
            if (token) {
                const response = await fetch(`${API_URL}/api/animals/?search=${text}`, {
                    method: "GET",
                    headers: {
                        Authorization: `Token ${token}`,
                        Accept: "application/json",
                        "Content-Type": "application/json",
                    },
                });
                return await response.json();
            } else {
                throw new Error(token);
            }
        } catch (error) {
            console.error("There was a problem with the fetch operation:", error);
            throw error;
        }
    };
    

    And now it works.