Search code examples
javascripthtmlreactjsreact-hooksfetch

printing filtered data getting different result


I'm new to React.js (using hooks) and want to learn by simply coding, my question is I am fetching data for example from ksngfr.com/something.txt and the data I'm getting from there is in the picture as you can see( in picture i have just put from 1-4, but it is from 1-50). For some reason when i'm for example writing in input '3' it gives me this(first picture). I have checked from internet and came up with this solution. I want to achieve this: when user writes in input for example number '3' it should go to data and check number 3 (which is 3:95426) and come back with just that result and nothing else, like one box (number 3) and another box its value '95426'. English is not my mother language, sorry for mistakes

enter image description here

data i'm fetching:

enter image description here

my code:

function App() {
  const [data, setData] = useState([]);
  const [searchResults, setSearchResults] = useState([]);
  const [searchTerm, setSearchTerm] = useState("");
  const obj = {};
  useEffect(() => {
    const fetchData = () => {
      let corsAnywhere = "https://cors-anywhere.herokuapp.com/";
      let something = "http://ksngfr.com/something.txt";
       fetch(corsAnywhere + something)
        .then((response) => response.text())
        .then((result) => {
          const theDataArr = result.replace(/\n/g, " ");
          const f = theDataArr.split(" ");
          setData(f);
        });
    };
    fetchData();
  }, []);
  data.forEach((d) => {
    var propertyK = d.split(":")[0];
    var propertyv = d.split(":")[1];
    obj[propertyK] = propertyv;
  });
  const k = Object.keys(obj);

  useEffect(() => {
    const results = k.filter((person) =>
      person.toLowerCase().includes(searchTerm)
    );
    setSearchResults(results);
  }, [searchTerm]);

  console.log(data);

  return (
    <div>
      <input
        type="text"
        value={searchTerm}
        placeholder="Search..."
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <div>
        {searchResults.map((value, index) => (
          <div>
            <div>
              <IndexBox key={index} index={index + 1} />
            </div>
            <div>
              <ValueBox key={index} value={value} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default App;


Solution

  • Ok if the fetch works then try this code.

    function App() {
       const [data, setData] = React.useState([]);
      const [searchResults, setSearchResults] = React.useState([]);
      const [searchTerm, setSearchTerm] = React.useState("");
    
      const fetchData = () => {
    let corsAnywhere = "https://cors-anywhere.herokuapp.com/";
    let something = "ksngfr.com/something.txt";
    fetch(corsAnywhere + something)
      .then((response) => response.text())
      .then((result) => {
        const theDataArr = result.replace(/\n/g, " ");
        const f = theDataArr.split(" ");
        setData(f);
      });
      };
    
      React.useEffect(() => {
    fetchData();
      }, [searchTerm]);
    
      React.useEffect(() => {
    if (data.length) {
      const mappedResult = data.map((d) => {
        var propertyK = d.split(":")[0];
        var propertyv = d.split(":")[1];
        return {
          key: propertyK,
          value: propertyv
        };
      });
      const results = mappedResult.filter((each) => each.key === searchTerm);
      console.log("result is: ", results);
      setSearchResults(results);
    }
      }, [data, searchTerm]);
    
      return (
    <div>
      <input
        type="text"
        value={searchTerm}
        placeholder="Search..."
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <div>
        {searchResults.map(({ key, value }, index) => (
          <div>
            <div>{`value is: ${value} and key is: ${key}`}</div>
          </div>
        ))}
      </div>
    </div>
      );
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>,
      rootElement
    );
    <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>