I’m new to JS and React and i’m currently working on a project using React.
The project in question is a social media app where you create posts.
I wanted to use fetch to get a list of “posts” and then use react to format them. I was able to get it to work from a post online, however I don’t quite understand the syntax.
Here is the code..
function App() {
const [posts, setPosts] = React.useState(null);
React.useEffect(() => {
fetch('/posts')
.then((resp) => resp.json())
.then((posts) => {
console.log(posts)
setPosts(posts);
});
}, []);
return (
<div>
{posts && posts.map((post)=> (
<div class="container">
<div class="row border mt-2">
<div class="col-12">
{post.owner}
</div>
<div class="col-12">
{post.content}
</div>
<div class="col-12">
{post.created_at}
</div>
<div class="col-12">
likes: {post.likes}
</div>
</div>
</div>
))}
</div>
)
}
ReactDOM.render(<App />, document.querySelector("#app"));
In particular I don’t really understand posts && posts.map((post)=> in the return statement. It confuses me that there is an AND (&&) conditional where I am returning both the “posts” array as well as a mapped version of the array? Is there something I’m missing.
Advertisement
Answer
&& is the boolean AND operator. This syntax is a trick that relies on the fact that it short circuits if the first operand is a false-y (usually undefined).
In a nutshell, here’s what’s happens:
- The left operand (
posts) is evaluated. - If it’s a false-y (e.g.,
undefined), it’s returned. - If it’s a truth-y, the right operand (
posts.map(...)) is evaluated and is returned.
It basically boils down to oneliners designed to check posts and if it’s defined, do something with it. An arguably more-readable way of writing this would be
if (!posts) {
return posts;
}
return posts.map(...);