I am trying to filter fetched blog posts by entering a user number in a input. This number should match the post userId and show only the posts 'written' by that given user (which is a number from 1 to 10 and each user have 10 posts).
Problem: When I enter a number in the input, posts disappear and doesn't filter anything. I am pretty sure than I am stuck with the filter function.
Thanks in advance!
function App(pst) {
const [posts, setPosts] = useState([]);
const [query, setQuery] = useState('');
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts/')
.then(response => response.json())
.then(json => setPosts(json))
}, [])
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<Router>
<NavBar />
<Switch>
<Route exact path='/'>
<Home />
<SearchBar
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<Grid container spacing={2} justify='center'>
{posts.filter((val) => {
if (query === '') {
return val
} else if (query === val.userId) {
return val
}
console.log(query);
}).map((pst) => (
<PostCard pst={pst} key={pst.id}/>
))}
</Grid>
</Route>
<Route exact path='/singlePost/:postId' component={SinglePost} />
<Route exact path='/PostList'>
<PostList pst={pst}/>
</Route>
</Switch>
</Router>
</ ThemeProvider>
);
}