Eastonco
Eastonco

Reputation: 105

How to setup a react state to use a list of a custom type

So I'm trying to find a way to update a react component when a list of results gets updated. The results are being displayed with a list.map statement. The obvious answer seems to be to change the variable to a react state however I can't find the correct syntax to initialize the state to an empty list of a custom type and still be able to map the results.

current working example that doesn't update the page:

var results: customType[] = [];

results.append(CustomTypeItem)

// API call that updates results when search is pressed

return({results.map((item, index) => (
   <Entry value={item} key={index} />
))});

What I've tried

const [results, setResults] = useState([]);

setResults([CustomTypeItem]) // throws error that type is not assignable to never

Any help would be extremely appreciated

Upvotes: 0

Views: 1413

Answers (2)

hellogoodnight
hellogoodnight

Reputation: 2129

const [results, setResults] = useState<any[]>([]);

Upvotes: 1

Thọ Đỗ Xu&#226;n
Thọ Đỗ Xu&#226;n

Reputation: 150

I think you just need to set an empty array as the default value of your state

const [list, setList] = useState([])

and then when you update the list state with setList(), your component will auto re-rendered to update the list's element, you can use Ramda's functions like update or remove

Upvotes: 0

Related Questions