Home > OS >  ReactJS: How to properly reset or handle data from state
ReactJS: How to properly reset or handle data from state

Time:02-17

I have this working, when the user goes to this page, this line of code executes:

interface Badge {
  id: string;
  badge_name: string;
  badge_description: string;
  img64: string;
}
    const [data, setData] = useState([] as any[]);
    const [isPending, setisPending] = useState(true);
    const [searchTerm, setSearchTerm] = useState("");

    const onSearchChange = (e: any) => {
        setSearchTerm(e.target.value);
      };

const setDataWithImg = useCallback(async (badges: Badge[]) => {
    let badgeWithImg: Badge[] = [];

    const base64Flag = "data:image/png;base64,";

    await Promise.all(
      badges.map(async (badge: any) => {

        const imgBuffer = badge.img_icon.data;
        const imgBase64 = bufferToBase64(imgBuffer);

        badge.imgBase64 = `${base64Flag}${imgBase64}`;

        badgeWithImg.push(badge);
      })
    );

    setData(badgeWithImg);
  }, []);
    
    const loadData = useCallback(async () => {
        console.log("loadData");
        try {
          setisPending(true);
          await BadgeService.loadData().then(
            (res) => {
              setDataWithImg(res.data);
              setisPending(false);
            },
            (error) => {
              setisPending(false);
            }
          );
        } catch (err) {
          console.log(err);
          setisPending(false);
        }
      }, [setDataWithImg]);
    
      useEffect(() => {
        loadData();
      }, [loadData]);

It will load the data from BadgeService.loadData and I have this function also that will search data from api, and this code will execute.

const onClickFilter = async (e: any) => {
    e.preventDefault();
    if (searchTerm === "") {
      loadData();
    } else {
      try {
        console.log("filterData");
        setisPending(true);
        await BadgeService.filterData({
          badge_name: searchTerm,
        }).then(
          (res) => {
            setDataWithImg(res.data);
            setisPending(false);
          },
          (error) => {
            setisPending(false);
          }
        );
      } catch (err) {
        console.log(err);
        setisPending(false);
      }
    }
  };

User has a search function and that code will execute, search function works fine, I want when user click filter with empty value in search, it will load the original loadData. I already tried console.log('Loaddata') to trace if my condition is working fine and it is ok, but when I check the network, it still executing the api call from filterData, not loadData

First load of the page:

enter image description here

When user fires search function:

enter image description here

Where user fires search function but empty search term:

enter image description here

Base on network logs:

enter image description here

The last request should be the badges only, not the with parameters..How I fix this? What Am I missing here?

Thank you!

CodePudding user response:

Looking at your code, your if check in onClickFilter function seems wrong.

you can do something like

if(!searchTerm){
 loadData();
}

Doing !searchTerm will return true for every "falsy" value (empty string, 0, null, false, undefined, NaN) whereas x == "" will only return true if x is null (or apparently undefined).

Please let me know if it works.

CodePudding user response:

I got may issue fix by doing this,

I have this code in my service:

 const loadData = () => {
      config["params"] = {};
      return axios.get(API_URL   "api/v1/badges", config).then((response) => {
        //console.log("from loaddata..");
        //console.log("load data", response);
        return response;
      });
    };
    
        const filterData = (data: any) => {
          config["params"] = {
            s: data,
          };
          return axios.get(API_URL   "api/v1/badges", config).then((response) => {
            console.log("from filterdata..");
            console.log("filter data", response);
            return response;
          })

;

I just added config["params"] = {}; this line of code to loadData

Thank you all!

  • Related