nearprotocolassemblyscript

How to write data back to storage?


I have a method called changePlaceName and i know it is working but after i call getPlaces to see the changes, i don't see the new place name instead i see the name when i created a new place.

this is changePlaceName

export function changePlaceName(placeId: u32, placeName: PlaceName): void {
  assert(placeId >= 0, 'Place ID must be >= 0');
  const place = Place.find(placeId);
  logging.log(place.name);  //gives "Galata Tower"
  place.name = placeName;
  logging.log(place.name);  // gives "New Galata Tower"
}

I need to save it somehow but I don't know how to do it.

I also tried this way;

export function changePlaceName(placeId: u32, placeName: string): void {
    assert(placeId >= 0, 'Place ID must be >= 0');
    const place = Place.find(placeId);
    logging.log(place.name);
    place.name = placeName;
    let newPlace = storage.get<string>(placeName, 'new galata tower');
    storage.set<string>(placeName, newPlace);
    logging.log('New place is now: ' + newPlace);
}

Now my visual code is complaining about the newPlace inside the storage.set

How do I fix it?


Solution

  • because you're using some kind of class to manage the concept of "Place", why not add an instance method to that class to save() the place once you've changed it's name?

    would help if you also posted your code for Place here, by the way

    my guess is that it looks something like this?

    !note: this is untested code

    @nearBindgen
    class Place {
      private id: number | null
      private name: string
    
      static find (placeId: number): Place {
        // todo: add some validation for placeId here
        const place = places[placeId]
        place.id = placeId
        return place
      }
    
      // here is the instance method that can save this class
      save(): bool {
        places[this.id] = this
      } 
    }
    
    // a collection of places where placeId is the index
    const places = new PersistentVector<Place>("p")