Issues arise due to data inconsistency stemming from the combination of a for loop and .map() function within the BACK4APP

I seem to be facing a challenge with data consistency caused by the for (const object of results) {} loop in the Sandbox Link at line41. The issue is that the results are displayed as a single result after using the .map() method. However, when I perform a console.log([toDoTasks]); in line79, all the results are displayed correctly.

Note: Please Check the SandBox console

  1. My question is whether there is an alternative way to fetch, for example
           const title: string = object.get("title");
    , the props for the object which would return all the results and not just a 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;

Answer №1

The issue lies in the method of setting the state with a new object, as highlighted by @crashmstr in the comment.

I have adjusted how the description text is rendered, but feel free to make further modifications if needed.

You can also view it in my sandbox here

Below is the updated 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() for updating 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() for updating 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;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to organize an array of objects by a specific key?

Experimented with the following approach: if (field == 'age') { if (this.sortedAge) { this.fltUsers.sort(function (a, b) { if (b.totalHours > a.totalHours) { return 1; } }); this ...

Creating a new TypeScript file via the command line: A step-by-step guide!

When I want to create a new file named main.ts, I try to write the command but it keeps showing an error. "bash: code: command not found" https://i.stack.imgur.com/cpDy3.png ...

TypeScript and Redux mapDispatchToProps are not in sync

Below is my React component written in TypeScript: import React from 'react'; import {connect, ConnectedProps} from 'react-redux'; import logo from './assets/logo.png'; // import { Counter } from './features/counter/Count ...

Angular2 - adding the authentication token to request headers

Within my Angular 2 application, I am faced with the task of authenticating every request by including a token in the header. A service has been set up to handle the creation of request headers and insertion of the token. The dilemma arises from the fact t ...

Storing Array Data in Ionic Using Native Storage - A Step-by-Step Guide

I want to implement a feature in my app where I can store translation history using Ionic Native Storage. Every time a word is translated, the translation action (date, translated word) will be saved in the storage. Then, when I navigate to the history pag ...

Type inference error in TypeScript occurs within a conditional statement when the condition relies on the output of a function call rather than a boolean expression

In my TypeScript code, I have a Linked List class that is working perfectly. The class includes a Node type and functions to add items to the list. type ListItem = number | string | object; class Node { private value: ListItem; private next: Node | nu ...

The discord.js TypeScript is throwing an error stating that the 'index.ts' file is missing when trying to run 'ts-node index.ts'

I have been working on creating a discord bot using discord.js and TypeScript. However, when I attempt to start the bot by running 'ts-node index.ts', I encounter the following error: Error: Cannot find module 'node:events' Require stac ...

Undefined Perception

Trying to obtain values from an observable, my subscription code within the component looks like this: this.checkoutService.getDisabledDate().subscribe (dates=>{this.formattedDate=dates}, (error:any)=>{console.log(error)}); When logging this.forma ...

retrieving a single object from $resource by passing a non-ID parameter

I am utilizing $resource to retrieve an array of objects. The method I am invoking is as follows: fetchTeamResource(): ng.resource.IResourceClass<ITeamResource> { return this.$resource("/api/Teams:teamId"); } Below is how I am i ...

Issue occurred while trying to render a React component with Typescript and WebPack

I am in the process of creating a basic React component that simply displays a page saying Hello. However, I'm encountering an error in my console. My compiler of choice is TypeScript. To set up my project, I am following this guide: https://github.co ...

Writing Data to Google Cloud Firestore Map using NextJS and Typescript with nested objects

I could use some assistance. I'm developing an application using NextJS (React), TypeScript, and Google Cloud Firestore. Everything seems to be working fine so far. However, I'm facing an issue with storing the address and phone number in a neste ...

Learn the best way to retrieve the highest number from a Array<String> in TypeScript or JavaScript

Can someone help me create a function in JS or TS that meets the following requirements? I am looking for a functional programming approach. ・Input type: Array(String) ・Output type: string or undefined Examples Input Result ["" ...

The devastation caused by typing errors in TypeScript

I have a preference: const settings = { theme: "light", }; and feature: const Feature = ({ setting }: Props) => ( <FeatureBlock> <FeatureValue scale="large" size={20}> {setting.theme} </Styled.FeatureValue> ...

Combining files/namespaces/modules in Typescript: How to do it?

Even though I believe the solution may be simple, understanding how to merge enums across multiple files is eluding me when reading through the documentation. // a.ts enum Color{ RED, BLUE } // b.ts enum Day{ MONDAY, TUESDAY } // c ...

Angular 5 Service Unit Testing for UPDATE Function

Currently, I am implementing a stepper feature with back, step, next steps. On the last step, when the user clicks 'done,' I need to call a service to update user data. While I have successfully tested the backStep() and nextStep() methods, I now ...

Troubleshooting a TypeScript error when trying to access an imported service in Angular 2

I've been working on creating a form that allows users to input required details, which will trigger a server call and save the information. However, no matter what I try, I keep encountering the following error: ORIGINAL EXCEPTION: TypeError: this.po ...

Dealing with a Typescript challenge of iterating over a tuple array to extract particular values

I am struggling with writing a function that extracts names from an array of tuples, where each tuple includes a name and an age. My current attempt looks like this: type someTuple = [string, number] function names(namesAndAges: someTuple[]) { let allNa ...

Encountering an issue with the property name despite already defining it

Encountering a property name error even though it has been defined Uncaught (in promise): TypeError: Cannot read property 'nome' of undefined export class HomePage { inscricao = "São Bernardo"; nome = "abc"; nomeInvalido; construc ...

Leveraging TypeScript 2.1 and above with extended tsconfig configurations

Recently, I have been experimenting with the new extends feature in the tsconfig.json file that allows developers to create a base configuration which other modules can extend or modify. Although it is functional, it is not working as anticipated. Strange ...

Creating a canvas that adjusts proportionally to different screen sizes

Currently, I am developing a pong game using Angular for the frontend, and the game is displayed inside an HTML canvas. Check out the HTML code below: <div style="height: 70%; width: 70%;" align="center"> <canvas id=&q ...