Prakhar Nigam
Prakhar Nigam

Reputation: 1

Getting Error while using usememo in React js?

I am trying to use the useMemo hooks in React js. According to the function we are sorting the array containing string in it. However when in returning the array back from the function it is just returning the first element of the array. Can you please help me understand what I am doing wrong in it.

import { useState } from "react";
import { useMemo } from "react";

export default function MemoExample2() {

  const [nameList, setNameList] = useState(['a', 'b', 'r', 'e']);

  const [sortedList] = useMemo(() => {
    console.log([...nameList].sort());
    return [...nameList].sort();


  }, [nameList]);

  function addLetter(e) {
    console.log()
    const letter = document.querySelector("#letter").value;

    setNameList([...nameList, letter]);
  }




  return <>
    <div>Unsorted: {nameList.join(' ,')}</div>
    <div>Sorted: {sortedList.join(',')}</div>
    <input type="text" id="letter" />
    <button onClick={addLetter}>Add Name</button>
  </>


}

The output should be a sorted array printed on HTML document.

Upvotes: 0

Views: 403

Answers (1)

Dhaval Gajjar
Dhaval Gajjar

Reputation: 2950

2 Issues with your code.

  1. As @Nick said you are using the variable as an array and from useMemo, you returning a single element not an array [].
  2. Also Don't use document.querySelector in React. You should be using useRef.

Following is the sample code which solves 2 issues and it works.

import { useMemo, useRef, useState } from "react";

export default function App() {
  const ref = useRef();
  const [nameList, setNameList] = useState(["a", "b", "r", "e"]);

  const sortedList = useMemo(() => {
    console.log([...nameList].sort());
    return [...nameList].sort();
  }, [nameList]);

  function addLetter(e) {
    const letter = ref.current.value;
    setNameList([...nameList, letter]);
  }

  return (
    <>
      <div>Unsorted: {nameList.join(", ")}</div>
      <div>Unsorted: {sortedList.join(", ")}</div>
      <input ref={ref} type="text" id="letter" />
      <button onClick={addLetter}>Add Name</button>
    </>
  );
}

Upvotes: 1

Related Questions