Home > Blockchain >  Data Inconsistency due to for loop and .map() from BACK4APP API
Data Inconsistency due to for loop and .map() from BACK4APP API

Time:10-18

I am having issues in my data consistency due to the for (const object of results) {} in the Sandbox Link line41 the Results are displayed as a single result after using .map() method however when i console.log([toDoTasks]); in line79 All the results are displayed normally ,

Note: Please Check the SandBox console

  1. My Question is there an alternative way to fetch for example const title: string = object.get("title"); the props for the object here which would return all the results not just the single result ?
import "./ExploreContainer.css";
import { useCallback, useState, useEffect } from "react";

const Parse = require("parse");

interface ContainerProps {}

const ExploreContainer: React.FC<ContainerProps> = () => {
  var [toDoTasks, setToDoTasks] = useState({
    objectId: "", //string
    title: "", //string
    description: "", //string
    task: "", //string
    isCompleted: Boolean(), //boolval
    createdAt: new Date(), //new Date()
    updatedAt: new Date() //new Date() to update the current time
  });

  //var query = new Parse.Query("ToDo");

  const readTasks = useCallback(async function (): Promise<Boolean> {
    // extend todo
    // Simple syntax to create a new subclass of Parse.Object.
    const ToDo: Parse.Object[] = Parse.Object.extend("ToDo");
    //parse query
    const parsequery: Parse.Query = new Parse.Query(ToDo);
    //const memoizedValue = useMemo(() =>  (""), [] );
    try {
      const results: Parse.Object[] = await parsequery.find();
      //ID MUST BE PARSED AND STRINGIFIED
      var resultsObj = JSON.parse(JSON.stringify(results));
      let id = resultsObj[0].objectId;
      //console.log(id);

      // alternative option
      //get by parameter
      //console.log(parsequery.equalTo('objectId', id));

      console.log(JSON.stringify(results));

      for (const object of results) {
        //Accessing the Parse Object attributes
        const title: string = object.get("title");
        const description: string = object.get("description");
        const task: string = object.get("task");
        const isCompleted: boolean = object.get("isCompleted");
        const createdAt: Date = object.get("createdAt");
        const updatedAt: Date = object.get("updatedAt");

        let resultsfix = {
          objectId: id, //string
          title: title, //string
          description: description, //string
          task: task, //string
          isCompleted: isCompleted, //boolval
          createdAt: createdAt, //new Date()
          updatedAt: updatedAt //new Date() to update the current time
        };
        setToDoTasks(resultsfix);
      }
      return true;
    } catch (error) {
      console.error("Error has been found in getAllTasks()"   error);
      return false;
    }
  }, []);

  useEffect(() => {
    readTasks();
  }, [readTasks]);

  return (
    <>
      {toDoTasks !== null &&
        toDoTasks !== undefined &&
        //ARRAY NEEDS TO BE ASSIGNED TO
        [toDoTasks].map((todo: any, item: any) => {
          //DISPLAY RESULTS HERE BUT IN GUI DISPLAYS ONLY SIGNLE RESULT
          console.log([toDoTasks]);
          console.log([todo?.title?.toLocaleLowerCase()]);
          return (
            <div key={todo   item}>
              <h5>{[todo?.title?.toLocaleUpperCase() || " "]}</h5>

              {[todo?.task?.toLocaleLowerCase() || " "]}

              <h5 className="ion-text-white">
                <strong>Description</strong>
              </h5>
              <em>{[todo?.description?.toLocaleLowerCase() || " "]}</em>

              <table>
                <thead>
                  <tr>
                    <th>ObjectId</th>
                    <th>Done?</th>
                    <th>Created </th>
                    <th>Updated </th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td> {JSON.stringify(todo?.objectId)}</td>
                    <td>
                      <p
                        className={
                          todo?.isCompleted === true
                            ? "todo_text-done"
                            : "todo_text"
                        }
                      >
                        {todo?.isCompleted?.toString()}
                      </p>
                    </td>
                    <td>{todo?.createdAt?.toDateString()}</td>
                    <td>{todo?.updatedAt?.toDateString()}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          );
        })}
    </>
  );
};

export default ExploreContainer;

CodePudding user response:

The main issue is how you're setting the state with a new object, as pointed out by @crashmstr in the comment.

I have changed how you render description text but now you can modify it if you want to.

you can see it in my sandbox as well Sandbox link

here is the modified code.

import "./ExploreContainer.css";
import { useCallback, useState, useEffect } from "react";

const Parse = require("parse");

interface ContainerProps {}

const ExploreContainer: React.FC<ContainerProps> = () => {
  var [toDoTasks, setToDoTasks] = useState([
    {
      objectId: "", //string
      title: "", //string
      description: "", //string
      task: "", //string
      isCompleted: Boolean(), //boolval
      createdAt: new Date(), //new Date()
      updatedAt: new Date() //new Date() to update the current time
    }
  ]);

  //var query = new Parse.Query("ToDo");

  const readTasks = useCallback(async function (): Promise<Boolean> {
    // extend todo
    // Simple syntax to create a new subclass of Parse.Object.
    const ToDo: Parse.Object[] = Parse.Object.extend("ToDo");
    //parse query
    const parsequery: Parse.Query = new Parse.Query(ToDo);
    //const memoizedValue = useMemo(() =>  (""), [] );
    try {
      const results: Parse.Object[] = await parsequery.find();
      //ID MUST BE PARSED AND STRINGIFIED
      var resultsObj = JSON.parse(JSON.stringify(results));
      let id = resultsObj[0].objectId;
      //console.log(id);

      // alternative option
      //get by parameter
      //console.log(parsequery.equalTo('objectId', id));

      console.log(JSON.stringify(results));
      const mappedData = [];
      for (const object of results) {
        //Accessing the Parse Object attributes
        const title: string = object.get("title");
        const description: string = object.get("description");
        const task: string = object.get("task");
        const isCompleted: boolean = object.get("isCompleted");
        const createdAt: Date = object.get("createdAt");
        const updatedAt: Date = object.get("updatedAt");

        let resultsfix = {
          objectId: id, //string
          title: title, //string
          description: description, //string
          task: task, //string
          isCompleted: isCompleted, //boolval
          createdAt: createdAt, //new Date()
          updatedAt: updatedAt //new Date() to update the current time
        };
        mappedData.push(resultsfix);
      }
      setToDoTasks(mappedData);
      return true;
    } catch (error) {
      console.error("Error has been found in getAllTasks()"   error);
      return false;
    }
  }, []);

  useEffect(() => {
    readTasks();
  }, [readTasks]);

  return (
    <>
      {/* //ARRAY NEEDS TO BE ASSIGNED TO MAP OVER VALUES
            //DISPLAY RESULTS HERE BUT IN GUI DISPLAYS ONLY SIGNLE RESULT */}

      <div>
        <table>
          <thead>
            <tr>
              <th>ObjectId</th>
              <th>description </th>
              <th>Done?</th>
              <th>Created </th>
              <th>Updated </th>
            </tr>
          </thead>
          <tbody>
            {toDoTasks.map((todo: any, item: any) => {
              <h5>{[todo?.title?.toLocaleUpperCase() || " "]}</h5>;

              {
                [todo?.task?.toLocaleLowerCase() || " "];
              }

              return (
                <>
                  <tr>
                    <td> {JSON.stringify(todo?.objectId)}</td>
                    <td>
                      <em>{[todo?.description?.toLocaleLowerCase() || " "]}</em>
                    </td>
                    <td>
                      <p
                        className={
                          todo?.isCompleted === true
                            ? "todo_text-done"
                            : "todo_text"
                        }
                      >
                        {todo?.isCompleted?.toString()}
                      </p>
                    </td>
                    <td>{todo?.createdAt?.toDateString()}</td>
                    <td>{todo?.updatedAt?.toDateString()}</td>
                  </tr>
                </>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
};

export default ExploreContainer;
  • Related