React Native – How to use AWS DataStore for local storage (2)?

How to save/ update a record?

type Station @model {
  id: ID!
  station_name: String!
  station_id: Int!
  created_at: Int!
}
    const savedRecords = await DataStore.query(StationModel, (c) =>
      c.station_id('eq', station.station_id)
    );

    if (savedRecords.length > 0) {
      await DataStore.save(
        StationModel.copyOf(savedRecords[0], (updated) => {
          updated.created_at = Date.now();
        })
      );
    } else {
      await DataStore.save(
        new StationModel({
          station_name: station.station_name,
          station_id: station.station_id,
          created_at: Date.now(),
        })
      );
    }

How to query and sort data?

      const list = await DataStore.query(StationModel, Predicates.ALL, {
        sort: (s) => s.created_at(SortDirection.DESCENDING),
      });

How to query a number of data?

      const list = await DataStore.query(StationModel, Predicates.ALL, {
        sort: (s) => s.created_at(SortDirection.DESCENDING),
        page: 0,
        limit: 5,
      });

How to delete a record?

      const toDelete = await DataStore.query(StationModel, (c) =>
        c.station_id('eq', station.station_id)
      );
      DataStore.delete(toDelete[0]);

Be the first to comment

Leave a Reply

Your email address will not be published.


*