Reputation: 1
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
Reputation: 2950
2 Issues with your code.
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