Home > Software design >  How resolve the error: Cannot assign to read only property 'message' of object 'Synta
How resolve the error: Cannot assign to read only property 'message' of object 'Synta

Time:01-28

I'm trying to write a code in the codesandbox, but it's with an error. I have to do a check through the ternary.

TypeError
Cannot assign to read only property 'message' of object 'SyntaxError: /src/components/SearchResults.js: Unexpected token (8:10)

   6 |       {filteredProducts().map((product) => {
   7 |         filteredProducts().length > 0 (
>  8 |           return (
     |           ^
   9 |             <div key={product.id}>
  10 |               <li>{product.title}</li>
  11 |             </div>'

To solve the problem I used the ternary with the ? and : Am I doing something wrong what could it be? Someone can help me?

Component with error

import React from "react";
const SearchResults = ({ filteredProducts }) => {
  return (
    <div>
      {filteredProducts().map((product) => {
        filteredProducts().length > 0 (
          return (
            <div key={product.id}>
              <li>{product.title}</li>
            </div>
          )
        ) : (
          return(
            <p>Item not found</p>
          )
        )
      })}
    </div>
  );
};

export default SearchResults;

Codesanbox

CodePudding user response:

you should check the length before the map statement like this:

import React from "react"

const SearchResults = ({ filteredProducts }) => {
  return (
    <div>
      {filteredProducts.length > 0 ? (
        filteredProducts().map((product) => (
          <div key={product.id}>
            <li>{product.title}</li>
          </div>
        ))
      ) : (
        <p>Item not found</p>
      )}
    </div>
  )
}

export default SearchResults

CodePudding user response:

you cannot have return inside (expression) becuase it is not a function

Also, the ternary syntax has "?" like this

 expressionIfTrue ? (take this) : (If exp not true take this)

import React from "react";
const SearchResults = ({ filteredProducts }) => {
  return (
    <div>
      {filteredProducts().map((product) => {
        filteredProducts().length > 0 ? (
          <div key={product.id}>
            <li>{product.title}</li>
          </div>
        ) : (
          <p>Item not found</p>
        );
      })}
    </div>
  );
};

export default SearchResults;
  • Related