Conditional If inside map() with Function

Asked

Viewed 54 times

-2

Hello! I have a line of code like this:

    if (searchQuery.length != 0) {
      return (
        <Row hidden>
          {searchQuery.map((res) => (

In this snippet of code, I’m trying to add a if shortly after the => ( with the keys "{ if...".

What I wish to do is: add one if so that only if "res.display" is true (in Strapi, as a boolean), to continue the code. That way, it doesn’t work (and several - 12 hours trying - other):

{ if ({res.display /*como true*/}) { 
    //todo o trecho de código executável
}

It returns me a syntax error, hoping that the "res.display" has a comma instead of a dot; perhaps wishing it was a parameter (because of the keys).

The whole project is that I have cards inside the site and I would like to hide the ones that are with false in the boolean "display" that I created at Strapi. Without the need to exclude them, to restore them when necessary; I saw, also, that in version 3.2 of Strapi, there is function of Publish/unpublish, but I am using 3.1.4, so, trying to update the packages, I totally broke the system.

Editing:

I tried to do as my friend @Jason Rabelo taught and had problems again. I’ll leave the entire code section so it can be understood better:

/* components/ServiceList/index.js */
import { useQuery } from "@apollo/react-hooks";
import { gql } from "apollo-boost";
import React, { useState } from 'react';
import Link from "next/link";
import LayerMoreInfo from "../../components/LayerMoreInformation";

import {
  Card,
  CardBody,
  CardImg,
  CardText,
  CardTitle,
  CardHeader,
  CardFooter,
  Collapse,
  Navbar,
  NavbarToggler,
  NavbarBrand,
  Nav,
  NavItem,
  NavLink,
  Container,
  Row,
  Col,
  Jumbotron,
  Button,
  Carousel,
  CarouselItem,
  CarouselControl,
  CarouselIndicators,
  CarouselCaption,
  Spinner
} from "reactstrap";

const QUERY = gql`
  {
    services {
      id
      name
      description
      image {
        url
      }
      header
      display
    }
  }
`;

function ServiceList(props) {

  const [collapse, setCollapse] = useState(false);
  const [status, setStatus] = useState('Closed');
  
  const onEntering = () => setStatus('Opening...');
  
  const onEntered = () => setStatus('Opened');
  
  const onExiting = () => setStatus('Closing...');
  
  const onExited = () => setStatus('Closed');
  
  const toggle = () => setCollapse(!collapse);

  const { loading, error, data } = useQuery(QUERY);
  if (error) return "Error loading services";
  //If services are returned from the GraphQL query, run the filter query
  //and set equal to variable serviceSearch
  if (loading) return ( <Spinner style={{ width: '5rem', height: '5rem', textAlign: "center", alignContent: "center" }}  color="primary" /> );
  if (data.services && data.services.length) {
    //searchQuery
    const searchQuery = data.services.filter((query) =>
      query.name.toLowerCase().includes(props.search)
    );
    if (searchQuery.length != 0) {
      return (
        <Row>
          {searchQuery.filter((res) => /* isso sendo um teste, baseado na solução do Jason:  {if (res.display) { return ( */

            <Col sm="4" key={res.id}>
              <Card style={{ margin: "20px 0px 20px 0px", textAlign: "center" }} className="layerCard">

                <CardHeader tag="h4">{res.header}</CardHeader>

                <CardBody style={{ height: "150px" }}>
                  <CardTitle tag="h5">{res.name}</CardTitle>
                  <CardText>{res.description}</CardText>
                </CardBody>

                <CardImg
                  top={true}
                  style={{ height: "180px", textAlign: "center" }}
                  src={`${res.image[0].url}`}
                  className="img-responsive"
                />
                <LayerMoreInfo id={res.id} />
                
              </Card>
            </Col>
          ))}

          <style jsx global>
            {`
              a {
                color: white;
              }
              a:link {
                text-decoration: none;
                color: white;
              }
              a:hover {
                color: white;
              }
              .card-columns {
                column-count: 3;
              }
            `}
          </style>
        </Row>
        //aqui a o fechamento do condicional if: );}}
      );
      } else {
      return <h1>No Services Found</h1>;
    }
  }

}

export default ServiceList;

Unfortunately, he answered me with several errors in keys and parentheses outside of this "{if (res.display..."; including in else of if (searchQuery.length != 0)

Issue 2:

I was able to solve the problem, based on a little observability and the answer from @Jason Rabelo. The solution lies between the answers, with my answer.

  • 1

    you tried to remove from the ? if(res.display key)

  • Yeah, buddy. It didn’t work.

2 answers

0


Good morning, my friend, as callbacks functions javascript does not need you make a structure if complete in this kind of situation, you can do so:

searchQuery.map((res) => res.display);

Remembering that in this case the function map, will return a array containing only the display results or an array containing all the true or false

if you want to filter and bring only all the items of a array where the display be it true, then you should use the function filter thus:

searchQuery.filter((res) => res.display);

if you find it best to use the full structure of if you can do this following way:

searchQuery.filter((res) => {
   if (res.display) {
     return true;
   }
);

I set just as an example for you, but as the variável is a booleana, then you don’t need to compare the value, just return it is already enough.

I hope I’ve helped

  • Jason, I’m going to edit my question to add the entire piece of code, so you’ll understand the problem better. I tried to do as you explained, but I had more difficulty, although it seems a great solution.

0

I was able to solve the problem, thanks to @Jason’s example and a little observation in the code itself. I realized there was a return just above, then simply "repeated" like this { if (res.display) { return (

    if (searchQuery.length != 0) {
      return (
        <Row>
          {searchQuery.map((res) => 
          { if (res.display) { return (
            <Col sm="4" key={res.id}>

Thank you very much, @Jason Rabelo.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.