CodeBlanks Logo Icon CodeBlanks

Note model

Set up the Note model and state.

The Note model and state

In this lesson we move the Note model into state. A note is an object with id, title and body fields. We will add the first note: { id: "1", title: "Shopping", body: "Milk, bread" }.

The initial value of the state will be a single-element array. This way the app shows one note ready when it opens. In later lessons we will learn how the user can add new notes; for now we see how the model lands in state. We will also read a field of a note: notes[0].title returns the title of the first note.

Practice Add the first note

Add the first note to the NotesApp component. Give useState the initial value [{ id: "1", title: "Shopping", body: "Milk, bread" }]. The component keeps returning <Text>Notes</Text>.

Starter code

App.js
// Import useState

function NotesApp() {
  // Start notes state with useState
  // Initial value is a single-element array with id, title and body

  return <Text>Notes</Text>;
}

Sample solution

App.js
import { useState } from "react";
import { Text } from "react-native";

function NotesApp() {
  const [notes, setNotes] = useState([{ id: "1", title: "Shopping", body: "Milk, bread" }]);
  return <Text>Notes</Text>;
}

Showing notes

To show the notes held in state on screen you use a list. In React Native FlatList is the most common choice; it is efficient for large lists. Each note is shown inside a Text.

In this lesson we will not move to FlatList yet; we will just print the first note's title with a simple Text. In later lessons we will show all notes as a list. Start small, then grow; this keeps projects solid. For now the point is to see how state is read.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Read the title field

Question
const firstTitle = notes[0].____;
Answer
const firstTitle = notes[0].title;

Explanation: notes[0].title returns the first note's title.

2 Which field of a Note is unique?

App.js
const note = { id: "1", title: "Alışveriş", body: "Süt" };
  • title
  • body
  • createdAt
  • id Correct answer

Explanation: answer: id. Two notes cannot share an id.

3 Match the state and fields

Term Meaning
useState Holds state
notes[0] First note
title Title field
id Unique id

All lessons in Intermediate