Search code examples
javascriptreactjsfetch

How to parse the response of fetch as JSON


My react code:

fetch("http://localhost:8080/getnames")
  .then(response => response.text())
  .then(data => {
  alert("data: "+data);
  alert("index: "+data.indexOf(value));
  data.indexOf(value) === -1 ? callback() : callback("DuplicateName")
})

if array is ["abc","def"] then data.indexOf("a") is > -1. Why? How to resolve this

What I want is exact match. how to accomplish that?


Solution

  • If the response is JSON, you have to parse it. You should use response.json() method instead of response.text():

    fetch("http://localhost:8080/getnames")
      .then(response => response.json())
      .then(data => {
      alert("data: "+data);
      alert("index: "+data.indexOf(value));
      data.indexOf(value)===-1?callback():callback("DuplicateName")
    })