Map function not rendering data in List item despite having data

155 Views Asked by At

I am receiving the list of tools data through mapStateToProp. I also looked after other similar issues which addressed issue via only one solution of adding return within map function, but still it doesn't work. Checked in logs the data is present and even used the ternary operator to evaluate if data is actually present, still it doesn't shows the else (code after the ':') portion

const DemoTools=({toolsListData})=>{

const [toolsList, setToolsList] = useState(toolsListData);

return (
<List>
{
  toolsList ?
    toolsList.map((tool,index)=>{
     return (
       <ListItem key={index}>
            <ListItemText primary={tool.name} />
       </ListItem>
    :<p>No Tools</p> //It never reaches here though
  )})
}
</List>
);
}

enter image description here The reason you are seeing data in this image, I have a search bar to search a tool, as soon as I enter text to search for a tool, or even clear the search box, the whole list is then visible.

const handleSearch = (value) => {
        let matchvalue = toolsListData.length > 0 ? toolsListData.filter(tool => tool.name.toLowerCase().includes(value.toLowerCase())) : [];
        setToolsList(matchvalue);
    }
2

There are 2 best solutions below

0
On

Found the exact issue. The tools list which I am fetching here came from GET api call, which is empty initially in first render cycle. So the by the time data is actually fetched the ListItem was already rendered. So I used a useEffect to monitor the toolsListData and then 'set' it thru setToolsList(toolsList);

useEffect(() => {
        if (toolsListData && toolsListData.length > 0)
            setToolsList(toolsListData);
    }, [toolsListData])

As soon as there is change in toolsListData it reflected immediately making it look like it rendered in first render cycle.

1
On

Your logic is syntactically incorrect (weird phrase). Here is the way that should work for you :-

 toolsList ?
    toolsList.map((tool,index)=>{
     return (
       <ListItem key={index}>
            <ListItemText primary={tool.name} />
       </ListItem>
     )})
    :<p>No Tools</p>