Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript-React: array not visible as component

todoApi.ts:

import axios, {AxiosResponse} from "axios";

const API_URL: string = "http://localhost:8080/api/v1/todo/";

export async function getTodos(filter: string): Promise<[]> {
    const response: AxiosResponse = await axios.get(API_URL, {
        headers: {
            filter: filter
        }
    });
    return await response.data;
}

Api response example:

[
    {
        "id": 1,
        "name": "Todo",
        "description": "Todo description",
        "done": false,
        "dateCreated": "2022-10-18",
        "deadline": "2022-10-19"
    },
    {
        "id": 2,
        "name": "Todo1",
        "description": "Todo1 description",
        "done": false,
        "dateCreated": "2022-10-18",
        "deadline": "2022-10-20"
    }
]

App.tsx: (excuse my bad naming conventions here)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import {getTodos} from "../api/todoApi";

let counter: number = 0;

export default function App(): JSX.Element {
    const [todos, setTodos] = useState([]);
 
    useEffect(() => {
        setInterval(() => {
            let _todos: ReactElement[] = [];

            getTodos(sessionStorage.getItem("search-key") as string).then((__todos) => {
                for (let i: number = 0; i < __todos.length; i++) {
                    const todo = __todos[i];
                    _todos.push(
                        <Todo key={counter} id={todo["id"]} name={todo["name"]}
                              description={todo["description"]}
                              dateCreated={todo["dateCreated"]} deadline={todo["deadline"]}
                              done={todo["done"] === "true"}/>
                    );
                    counter++;
                }
            });

            // @ts-ignore
            setTodos(_todos);
        }, 500);
    }, []);

    return (
        <>
            <div id={"todos"}>
                // some other components
                {todos}
                // some other components
            </div>
        </>
    );
}
  • The array of to-dos doesn’t render although when going to react elements or logging the
    to-dos array I get the correct result.
  • Todo component just returns a div with class todo and an h1 for every prop.

>Solution :

note: Storing your components in the state is a bad idea. Instead, store the data, and then map over the data to compose the components


Your issue is coming from the fact that you’re loading the promise (.then) after you set your state (setTodos(_todos);) which means _todos is an empty array.

If you move the setTodos(_todos); below your for(){} loop, it will work. However, again, it is bad practice, and I urge you to continue research into better ways to do this 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading