#deletelist
Explore tagged Tumblr posts
Text
i guess i cant really relate to ppl being extremely embarrassed about having liked something bad like i know myself. i know what i like and i know what i saw in that piece of shit. and on the other side of things, sometimes realizing something you like sucks dick is the most freeing experience ever.
0 notes
Text
october bmc idea wordvomit listed like a challenge prompt list cuz people are doing that now* i made up for myself just now bc for some reason im really into halloween this year
*this doesnt work as an actual prompt list and isnt intended to be one
squip jeremy vaugely frankensteinesque swap au (the swap part is that the squip is the human (frankenstein) and jeremy is the scifi creature (monster) but really its not actually based off of the story at all bc i #havent read it so its just the vague idea of it)
zombie richjer?
bmc lsoh au jeremy commiting premeditated murder
chloe and christine commiting involuntary manslaughter (christine my guilty conscience queen)
richjake post halloween misery
pinkberry still beefing when theyre like 25 and in the workforce (romantically) (situationship) (scary) its fall themed so close enough
squip x audrey ii? team up? audrey ii eats a squip? audrey ii eats multiple squips? and feeds them to its little baby audrey iis?
chloejake get back together for the 7th time (scary2)
jennachristine uncover buried halloween themed school curse lore (meeting->get together type of thing)
typical drama club haunted theater ghost story but shit actually starts happening (optionally its just the squip fucking with the electronics or something)
im hungry af rn
boyfs jack o lantern carving (awww ❤ awwww ❤ so cutesy awwwww)
some devil angel shit sorry i love devil angel shit
i ❤ the headless horseman sorry off topic im already talking about halloween so whatever
MORE SQUIP PSYCHOLOGICAL HORROR 😍😍😍😍😍 (not halloween specific i just like that shit)
squipped christine focus i ❤ squipped christine
be more chill but the squip is fungus
be more chill but the plot is the exact same but squips have vampire imagery instead of zombie imagery
be more chill but its evil
.
ok whatever
#my posts#i want this on this account but not to show up in searches cause its so specific to the stuff i like..... whateverrrr you cant win them all#deletelist?
1 note
·
View note
Photo
Rails2.7 Rails6 Docker React環境でシンプルCRUD実装 https://ift.tt/2UykrYB
streampackのminsuです。 以前の記事で Docker + Rails + React の環境構築を行いindexページの表示まで行ったのでCRUD機能を追加します。 ですが期間も空いているため、折角なので以前の環境である
Rails 5.1.4
Ruby 2.4.1
mysql 5.7
ではなく、新しい環境で作り直します。
最新版確認 https://rubygems.org/gems/rails https://www.ruby-lang.org/ja/downloads
作成環境
Rails 6.0.2
Ruby 2.7
mysql 5.7
ファイルの用意
Gemfile Gemfile.lock Dockerfile docker-compose.yml を作成します。
Gemfile
source "https://rubygems.org" gem "rails", "6.0.2"
Gemfile.lock
FROM ruby:2.7.0 RUN apt-get update -qq && \ apt-get install -y \ nodejs \ build-essential RUN apt-get update && apt-get install -y curl apt-transport-https wget && \ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \ echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \ apt-get update && apt-get install -y yarn RUN mkdir /app WORKDIR /app ADD Gemfile* /app/ RUN bundle install -j4 --retry 3 ADD . /app WORKDIR /app CMD ["bundle", "exec", "puma", "-C", "config/puma.rb"]
docker-compose.yml
version: '3' services: db: image: mysql:5.7 command: mysqld --character-set-server=utf8 --collation-server=utf8_unicode_ci ports: - "4306:3306" environment: - MYSQL_ROOT_PASSWORD=root volumes: - mysql_vol:/var/lib/mysql app: build: . command: /bin/sh -c "rm -f /app/tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'" volumes: - .:/app ports: - "3000:3000" depends_on: - db volumes: mysql_vol:
rails app作成
rails new
rails new を行います。
$ docker-compose run app rails new . --force --database=mysql
db設定を変更します。
database.yml
username: root password: root #docker-compose.ymlのMYSQL_ROOT_PASSWORD host: db #docker-compose.ymlのサービス名
今回も gem react-railsを利用するのでGemfileに追記します。
Gemfile
gem 'react-rails'
再度 build して
$ docker-compose build
reactを使うので下記コマンドを実行
$ docker-compose run app rails webpacker:install $ docker-compose run app rails webpacker:install:react $ docker-compose run app rails generate react:install
model 作成
$ docker-compose run app rails g model List title:string description:string $ docker-compose run app rails db:create $ docker-compose run app rails db:migrate
かなりの数の warning 出てきた。 Ruby 2.7.0に対応していないgemが存在することに起因しているようで非表示にすることもできる* が��要なwarningも見逃す可能性があるのでスルーすることにする。 *bash_profileにexport RUBYOPT='-W:no-deprecated -W:no-experimental'を追加
controller 作成
lists controller と view を作成
$ docker-compose exec app rails g controller Lists index
lists_controller.rb
class ListsController < ApplicationController def index @lists = List.all end end
index.html.erb
<%= react_component 'ListsIndex', lists: @lists %>
react_component タグを用いてreactを呼び出します。
react file 作成
viewから呼び出すreact fileを実装していきます。
$ rails g react:component ListsIndex
コマンドで app/javascript/components/ListsIndex.js が作成されるので編集します。
ListsIndex.js
import React from "react" import PropTypes from "prop-types" export default class Lists extends React.Component { constructor(props){ super(props) this.state = { lists: [] }; } componentDidMount(){ this.setState({ lists: this.props.lists }) } render () { return ( <div> <table> <thead> <tr> <th>ID</th> <th>Title</th> <th>Description</th> </tr> </thead> <tbody> {this.state.lists.map((list) => { return ( <tr key={list.id}> <td>{list.id}</td> <td>{list.title}</td> <td>{list.description}</td> </tr> ); })} </tbody> </table> </div> ); } }
動作確認
List モデルに適当な値を保存して動作確認をしてみます。
無事に一覧が表示されました。
simple CRUD の実装
railsにapiを追加します。 apiで行うアクションは index, create, update, destroy です。
/api/v1/xxxでアクセスできるようにrouteを設定し、controllerを追加します。
routes.rb
Rails.application.routes.draw do get 'lists/index' namespace :api do namespace :v1 do resources :lists, only: [:index, :create, :update, :destroy] end end end
app/controllsers/api/v1/lists_controllser.rb
class Api::V1::ListsController < ApplicationController protect_from_forgery with: :null_session def index render json: List.all end def create list = List.create(list_params) render json: list end def update list = List.find(params[:id]) list.update(list_params) render json: list end def destroy List.destroy(params[:id]) end private def list_params params.require(:list).permit(:id, :title, :description) end end
controllerには基本的なメソッド、そしてprotect_from_forgery with: :null_sessionを記述しました。
http://localhost:3000/api/v1/listsでindexが呼び出されリストが取得できるはずです。
index
reactからapiを利用してlists を取得します。 componentDidMountを書き換えます。
ListsIndex.js
componentDidMount(){ this.getIndex(); } getIndex(){ fetch('/api/v1/lists.json') .then((response) => {return response.json()}) .then((data) => {this.setState({ lists: data }) }); }
delete
delete機能を実装します。 ボタンを追加
return ( <div> <div>this is list</div> <table> <thead> <tr> <th>ID</th> <th>Title</th> <th>Description</th> <th>function</th> </tr> </thead> <tbody> {this.state.lists.map((list) => { return ( <tr key={list.id}> <td>{list.id}</td> <td>{list.title}</td> <td>{list.description}</td> <td> <button onClick={() => this.handleDelete(list.id)}>delete</button> </td> </tr> ); })} </tbody> </table> </div> );
ボタンから呼び出されるhandleDeleteを実装します。
handleDelete(id){ fetch(`http://localhost:3000/api/v1/lists/${id}`, { method: 'DELETE', headers: { 'Content-Type': 'application/json' } }) .then((response) => { console.log('List was deleted'); this.deleteList(id); }) } deleteList(id){ let lists = this.state.lists.filter((list) => list.id != id) this.setState({ lists: lists }) }
apiでのdestroyだけではstateの値は変わらないので、画面は更新されません。 そのためdeleteListにてstateの値を変更しています。
constructorに下記も追記します。
constructor(props){ ... this.getIndex = this.getIndex.bind(this); this.handleDelete = this.handleDelete.bind(this); this.deleteList = this.deleteList.bind(this); }
画面を確認すると deleteボタンが追加されており、要素の削除が行えます。
create
要素追加のformを作成します。 stateにてformの値を管理するために下記のように追記します。
constructor(props){ super(props) this.state = { // lists: this.props.lists lists: [], form: { title: "", description: "", } }; ...
各inpuフォームとaddボタンを追加
return ( <div> <div>this is list</div> <table> <thead> <tr> <th>ID</th> <th>Title</th> <th>Description</th> <th>function</th> </tr> </thead> <tbody> {this.state.lists.map((list) => { return ( <tr key={list.id}> <td>{list.id}</td> <td>{list.title}</td> <td>{list.description}</td> <td> <button onClick={() => this.handleDelete(list.id)}>delete</button> </td> </tr> ); })} <tr> <td></td> <td><input type="text" value={this.state.form.title} onChange={e=>this.handleChange(e,'title')} /></td> <td><input type="text" value={this.state.form.description} onChange={e=>this.handleChange(e,'description')} /></td> <td><button onClick={() => this.handleCreate()}>add</button></td> </tr> </tbody> </table> </div> ); }
ここで利用するhandleChangeとhandleCreateを実装します。 handleChangeではinputフォームの入力値をstateにて管理させています。
handleChange(e,key){ let target = e.target; let value = target.value; let form = this.state.form; form[key] = value; this.setState({ form: form }); }
handleCreateではapiのcreateメソッドを呼び出して要素の追加を行います。 追加後はstateのlistsの更新と inputフォームの値のリセットを行なっています。
handleCreate(){ let body = JSON.stringify({ list: { title: this.state.form.title, description: this.state.form.description } }) fetch('http://localhost:3000/api/v1/lists', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: body, }) .then((response) => {return response.json()}) .then((list)=>{ this.addList(list); this.formReset(); }) } addList(list){ this.setState({ lists: this.state.lists.concat(list) }) } formReset(){ this.setState({ form:{ title: "", description: "" } }) }
constructorに下記を追記
this.handleChange = this.handleChange.bind(this); this.addList = this.addList.bind(this); this.formReset = this.formReset.bind(this);
画面を確認するとcreate用のinputフォームが追加され、addボタンのクリックにより要素の追加を行えます。
完成したListIndex.js
ListIndex.js
import React from "react" import PropTypes from "prop-types" class ListsIndex extends React.Component { constructor(props){ super(props) this.state = { // lists: this.props.lists lists: [], form: { title: "", description: "", } }; this.getIndex = this.getIndex.bind(this); this.handleDelete = this.handleDelete.bind(this); this.deleteList = this.deleteList.bind(this); this.handleChange = this.handleChange.bind(this); this.addList = this.addList.bind(this); this.formReset = this.formReset.bind(this); } componentDidMount(){ this.getIndex(); } getIndex(){ fetch('/api/v1/lists.json') .then((response) => {return response.json()}) .then((data) => {this.setState({ lists: data }) }); } handleDelete(id){ fetch(`http://localhost:3000/api/v1/lists/${id}`, { method: 'DELETE', headers: { 'Content-Type': 'application/json' } }) .then((response) => { console.log('List was deleted'); this.deleteList(id); }) } deleteList(id){ let lists = this.state.lists.filter((list) => list.id != id) this.setState({ lists: lists }) } handleChange(e,key){ let target = e.target; let value = target.value; let form = this.state.form; form[key] = value; this.setState({ form: form }); } handleCreate(){ let body = JSON.stringify({ list: { title: this.state.form.title, description: this.state.form.description } }) fetch('http://localhost:3000/api/v1/lists', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: body, }) .then((response) => {return response.json()}) .then((list)=>{ this.addList(list); this.formReset(); }) } addList(list){ this.setState({ lists: this.state.lists.concat(list) }) } formReset(){ this.setState({ form:{ title: "", description: "" } }) } render () { return ( <div> <table> <thead> <tr> <th>ID</th> <th>Title</th> <th>Description</th> <th>function</th> </tr> </thead> <tbody> {this.state.lists.map((list) => { return ( <tr key={list.id}> <td>{list.id}</td> <td>{list.title}</td> <td>{list.description}</td> <td> <button onClick={() => this.handleDelete(list.id)}>delete</button> </td> </tr> ); })} <tr> <td></td> <td><input type="text" value={this.state.form.title} onChange={e=>this.handleChange(e,'title')} /></td> <td><input type="text" value={this.state.form.description} onChange={e=>this.handleChange(e,'description')} /></td> <td><button onClick={() => this.handleCreate()}>add</button></td> </tr> </tbody> </table> </div> ); } } export default ListsIndex
まとめ
Ruby2.7, Rails6 Docker react での環境構築 reactからのrails api利用の実装を行いました。 自分用のまとめですが、誰かの助けとなれば幸いです。
元記事はこちら
「Rails2.7 Rails6 Docker React環境でシンプルCRUD実装」
March 31, 2020 at 02:00PM
0 notes
Text
Using Mobx As A State Manager In React Native Applications
About The Author
Fortune Ikechi is a Frontend Engineer based in Rivers State Nigeria. He is a student of the University of Port-Harcourt. He is passionate about community and … More about Fortune …
MobX is one of the many state management tools available to React developers. In this tutorial, Fortune Kay explains what MobX is and how you can use it in your React applications by building one from scratch.
State management is an integral part of developing JavaScript applications especially React and React Native applications. In this tutorial, we are going to learn how to use the MobX library for state management; understand the core concepts, some use cases and build a simple example.
Note: Basic knowledge of Javascript and React Native will be of great benefit as you work through this tutorial.
Using MobX In React Applications
State is the data that your component(s) is working with — it holds the data that a component requires and it dictates what a component renders. State management is the process of managing how the state gets updated and passed from one component to another. Monitoring and working with data in an application can be difficult and that’s the need for state management libraries. Handling all the data for your application can be a little daunting especially when your application grows in size and complexity, building your own state management tool is not just time-consuming but difficult, This is why you might want to use a state management library.
However, it is important to know that state isn’t the only data that a component renders, components can also render props passed down to it.
Options For State Management
State management libraries for React Native applications include; React Context API, Redux, MobX and Unstated Next.
Although these state managers each have their advantages and disadvantages, I personally recommend MobX because of its simplicity, minimal boilerplate code — it doesn’t require you change your code, this is because in its core, MobX is and looks like JavaScript; you don’t need a change of architecture to support it (unlike RedUX and to a lesser extent Context).
In fact it’s such an invisible abstraction that in many cases if you take out all of the MobX code — the @observable, @computed, @action and observer decorators, your code will work exactly the same (though it’ll have some performance issues) and it’s not limited to a global state. These are some reasons to go forward with MobX as a state manager of choice for your React Native applications.
Although it’s also important to note some issues with using MobX as a state manager, some of which include its avoidance of rules on how to implement it and MobX can be difficult to debug especially when you change state directly in a component without using the @actions parameter.
What Is MobX?
According to the official documentation, MobX is a battle-tested library that makes state management simple and scalable by transparently applying functional reactive programming. MobX treats your application like a spreadsheet. The logic is that Anything that can be derived from the application state, should be done automatically.
MobX state architecture. (Large preview)
Core Principles And Concept Of MobX
MobX differentiates itself from other state managers with the following concepts.
1. State
State is the data your application holds — it’s roughly the entire contents of its memory. This also applies to your components.
2. Derivations
In MobX, anything that can be derived from the state without interactions is a derivation. Examples of derivations include:
User interface,
Backend add-ons such as changes to a server.
MobX has two mains types of derivations:
Computed values Computed values are mostly values that can be derived from a current state using pure functions.
Reactions Reactions in derivations are side effects that happen as a results of changes in your application state. They are similar to a computed value, but instead of producing a new value, a reaction produces a side effect for things like printing to the console, making network requests, incrementally updating the React component tree to patch the DOM, and so on.
A golden rule when using MobX is that when creating a value based on the current state, use a computed value.
3. Actions
Unlike derivations, actions are code that cause changes to an application state — code that changes the state. They are anything that modifies the state. With MobX you can make it explicit in your code, Actions are mostly user events such as inputs, backend data pushes or even scheduled events.
To better understand Actions, let’s look at an example from the MobX documentation.
class Ticker { @observable tick = 0 @action increment() { this.tick++ // 'this' will always be correct } } const ticker = new Ticker() setInterval(ticker.increment, 1000)
Here, we set an @observable tick with an initial value of 0. Next, we created a function increment that is also an action that updates the initial value once a tick is made every second.
Observables In MobX
Observables or observable values in MobX are mostly JavaScript primitives, plain objects, classes, arrays and maps. They’re mostly used by first declaring an observable and adding a value to it and then calling it by adding an @observable as shown below:
observable(value) @observable classProperty = value
Store Architecture Approach In MobX
MobX principal architecture includes parts and ideas such as services, store, view models and containers — some of which are explained below.
Service This is usually a function called from a container; they can be used to get data from APIs and be added to the store.
Store As the name implies, this is the central place of the state used by an application. Usually in MobX, these include the observables, variables, actions and computed properties.
Container This calls service and puts data from View Model to View Component as React props (should be marked with @observer decorator).
MobX In React And Native Applications
For learning purposes, in this tutorial, we are going to build a simple list app that will allow a user to add, view, and delete list items. We will be using MobX as a state manager in this application to add lists, update and delete them from the app state. However, it’s important to note that you already understand the basic concepts of JavaScript and React.
Without further ado, let’s start!
Setting Up Your Environment
Now that we know how what MobX is and how it works, let me walk you through setting up your project.
First, let’s create a project with the following, write the following code on your terminal to initialise a project:
npx create-react-app listapp
The above code will create a bare React application using the create-react-app package. Move into the project directory:
cd listapp
For this app, we will need three components:
TitleInput This will contain the title for our project and an input form for adding lists.
List This will be an input form that would allow a user to add a list. It will have an add button to add our list items.
ListsDisplay This component will display all of the user list items and also a delete button that’s automatically generated when a user adds a list item.
We will use a Store.js to contain the app state and methods to modify it similar to RedUX. Let’s outline what they will be used for.
mobx This is the state manager we will be using for this project.
mobx-react This is the official React bindings for MobX.
bootstrap We will be using bootstrap version 4.5 to style our project.
uuid This is used to automatically create keys for deleting lists.
Having done that, let’s go ahead and install these packages. I will be installing them with an npm alternative done in yarn:
yarn add mobx mobx-react [email protected] uuid
Once the packages are installed, we will start our app in development mode by running the code below in our terminal:
yarn start
Setting Up Our App Store
Let’s create a store for our project. First, create a file in the root directory of our project called ListStore, this will be the central location of our app state.
For this app, we will need to create a ListStore in order not to repeat ourselves when we use it in other app components.
/*** src/Store.js ***/ import { observable, action, computed } from "mobx"; import { v4 } from "uuid"; export class List { @observable value @observable done constructor (value) { this.id = v4() this.value = value } } export class ListStore { @observable lists = [] @observable filter = "" @action addList = (value) => { this.lists.push(new List(value)) } @action deleteList = (list) => { this.lists = this.lists.filter(t => t !== list) } @computed get filteredLists () { const matchCase = new RegExp(this.filter, "i") return this.lists.filter(list=> !this.filter || matchCase.test(list.value)) } }
In the code above, we imported three functions from mobx.
observable This holds a variable which can be updated in the event of a change in state.
action Used to modify the application state.
computed Values that can be derived from the existing state or other computed values, it changes after a state gets modified.
The class List has two object values which are done and value which will hold the initial state of the app and the modification in the case of changes.
We want our new list to automatically create a key so that we can automatically get a delete button once a list is created, Here uuid is used to automatically create keys in our application.
Next, we added an addList function that will add lists when clicked by using the .push() method to push the list in the array we already created in the @observable lists array.
The deleteList function accepts List as a property which is supposed to be the item the user wants to remove. Then we set the value of this.Lists to a new array after we have removed the selected item.
Both addLists and deleteList are actions because they modify the state of our app when changes are made.
Initializing The MobX Store
Next on our list is to import our store in our App.js and use it in our project.
import React from 'react'; import Navbar from "./components/navbar"; import ListDisplay from "./components/ListDisplay"; import {ListStore} from './ListStore'; function App() { const store = new ListStore() return ( <div> <Navbar store={store}/> <ListDisplay store={store}/> </div> ); } export default App;
Here we imported the TitleInput and ListDisplay components. Then we initialized the store in our App.js in order to be able to pass it as props to the TitleInput and ListDisplay components.
Normally this will throw an error because we’ve not worked on the other components, so let’s do that. Let’s build out the ListDisplay component.
ListDisplay
This component displays all of our added lists and also automatically generates a delete button once a new list is added.
import React from 'react' import List from "./List"; import { observer } from 'mobx-react'; function ListDisplay(props) { const { deleteList, filteredLists } = props.store return ( <div> <div className="container"> {filteredLists.map(list => ( <List key={list.id} list={list} deleteList={deleteList} /> ))} </div> </div> ) } export default observer(ListDisplay)
For this component, we created a function ListDisplay and made it an observer, we also destructure the list and deletelist functions from the store, by doing this, we made it easier to pass then as object props.
Next, we map through filteredLists to return the lists, which we then use in building the individual list by passing the returned item as props to the List component.
Once done, our component should look like this with lists added:
Lists displayed by `ListDisplay` component. (Large preview)
Next is to add a List and TitleInput components.
List Component
Just like our other components, our List component will export the list as an observer in order to help the store watch it for changes.
import React from 'react' import { observer } from 'mobx-react' function List(props) { return ( <div className="card"> <div className="card-body"> <div className="d-flex justify-content-between align-items-center"> <p className={`title ${props.list.done ? "text-secondary" : ""}`}> {props.list.value} </p> <div> <button onClick={props.deleteList.bind(this, props.list)} className="btn btn-danger font-weight-bold py-2 px-5 ml-2"> Delete </button> </div> </div> </div> </div> ) } export default observer(List)
I used the bootstrap to create cards in the first set of divs and also align the delete icon to move towards the right-hand side of the app. First, we created a card component to handle our list and then we created a button tag for the delete button that will accept two objects of this and pass a prop to the list, this will on click, will remove the selected list item from the lists in the page.
A single list component with the delete button. (Large preview)
Next is to our TitleInput which will contain our input form for adding lists and the title for the project.
TitleInput
Similar to our other projects, we will be adding an @observer function so that the component will be able to accept props from the app Store.
import React, { useState } from 'react' import { observer } from 'mobx-react' function Navbar(props) { const [value, setValue] = useState("") const {addList} = props.store const prepareAddList = (e) => { e.preventDefault() addList(value) setValue("") } return ( <div className="container mt-3"> <h1 className="title">List App</h1> <form onSubmit={prepareAddList} className="form-group"> <div className="row ml-lg-2"> <input className="form-control-lg col-12 col-lg-9 col-sm-12 mr-3 border border-secondary" value={value} type="text" onChange={(e) => setValue(e.target.value)} placeholder="Enter list" /> <button className="col-lg-2 col-5 col-sm-5 mt-2 mt-lg-0 mt-sm-2 btn btn-lg btn-success font-weight-bold"> Add to List </button> </div> </form> </div> ) } export default observer(Navbar)
First, we initialized an initial state. Using React Hooks, we added an initial state called values which we set to an empty string. We use this to hold the value of what is entered in the input field. To know more about React Hooks, you can check out this article by David Abiodun.
Then we called an object for adding lists to the store addList and passed it as props from the app store.
Next we created a function preparedAddList to accept an event object for the input forms, we also added a button for adding the lists manually on click.
Almost done, we need to restart our project server by running:
yarn start
And our TitleInput should look like this:
Title and input component. (Large preview)
We are now done with all of our app components, so let’s assemble it in our App.js. To do that, we need to import our components titleInput and ListDisplay. We also need to import our store from the Store component.
In order for MobX to work in our App, we need to pass the MobX store as props in our App and individual components so that they get the properties and functions in the store.
import React from 'react'; import Navbar from "./components/navbar"; import ListDisplay from "./components/ListDisplay"; import {ListStore} from './ListStore'; function App() { const store = new ListStore() return ( <div> <Navbar store={store}/> <ListDisplay store={store}/> </div> ); } export default App;
Our app should look like this when completed:
(Large preview)
Conclusion
MobX is a great state manager especially for React-based applications, building our list app, we’ve learned the basic concepts of MobX, state, derivations, and actions. A working version of this app can be found here:
You can take this further by using MobX in the next application you build that involves the management of state. I’d love to see what new things you come up with. You can read more on MobX and state management applications in the references below.
Resources And References
(ks, ra, yk, il)
Website Design & SEO Delray Beach by DBL07.co
Delray Beach SEO
source http://www.scpie.org/using-mobx-as-a-state-manager-in-react-native-applications/ source https://scpie1.blogspot.com/2020/08/using-mobx-as-state-manager-in-react.html
0 notes
Text
Using Mobx As A State Manager In React Native Applications
About The Author
Fortune Ikechi is a Frontend Engineer based in Rivers State Nigeria. He is a student of the University of Port-Harcourt. He is passionate about community and … More about Fortune …
MobX is one of the many state management tools available to React developers. In this tutorial, Fortune Kay explains what MobX is and how you can use it in your React applications by building one from scratch.
State management is an integral part of developing JavaScript applications especially React and React Native applications. In this tutorial, we are going to learn how to use the MobX library for state management; understand the core concepts, some use cases and build a simple example.
Note: Basic knowledge of Javascript and React Native will be of great benefit as you work through this tutorial.
Using MobX In React Applications
State is the data that your component(s) is working with — it holds the data that a component requires and it dictates what a component renders. State management is the process of managing how the state gets updated and passed from one component to another. Monitoring and working with data in an application can be difficult and that’s the need for state management libraries. Handling all the data for your application can be a little daunting especially when your application grows in size and complexity, building your own state management tool is not just time-consuming but difficult, This is why you might want to use a state management library.
However, it is important to know that state isn’t the only data that a component renders, components can also render props passed down to it.
Options For State Management
State management libraries for React Native applications include; React Context API, Redux, MobX and Unstated Next.
Although these state managers each have their advantages and disadvantages, I personally recommend MobX because of its simplicity, minimal boilerplate code — it doesn’t require you change your code, this is because in its core, MobX is and looks like JavaScript; you don’t need a change of architecture to support it (unlike RedUX and to a lesser extent Context).
In fact it’s such an invisible abstraction that in many cases if you take out all of the MobX code — the @observable, @computed, @action and observer decorators, your code will work exactly the same (though it’ll have some performance issues) and it’s not limited to a global state. These are some reasons to go forward with MobX as a state manager of choice for your React Native applications.
Although it’s also important to note some issues with using MobX as a state manager, some of which include its avoidance of rules on how to implement it and MobX can be difficult to debug especially when you change state directly in a component without using the @actions parameter.
What Is MobX?
According to the official documentation, MobX is a battle-tested library that makes state management simple and scalable by transparently applying functional reactive programming. MobX treats your application like a spreadsheet. The logic is that Anything that can be derived from the application state, should be done automatically.
MobX state architecture. (Large preview)
Core Principles And Concept Of MobX
MobX differentiates itself from other state managers with the following concepts.
1. State
State is the data your application holds — it’s roughly the entire contents of its memory. This also applies to your components.
2. Derivations
In MobX, anything that can be derived from the state without interactions is a derivation. Examples of derivations include:
User interface,
Backend add-ons such as changes to a server.
MobX has two mains types of derivations:
Computed values Computed values are mostly values that can be derived from a current state using pure functions.
Reactions Reactions in derivations are side effects that happen as a results of changes in your application state. They are similar to a computed value, but instead of producing a new value, a reaction produces a side effect for things like printing to the console, making network requests, incrementally updating the React component tree to patch the DOM, and so on.
A golden rule when using MobX is that when creating a value based on the current state, use a computed value.
3. Actions
Unlike derivations, actions are code that cause changes to an application state — code that changes the state. They are anything that modifies the state. With MobX you can make it explicit in your code, Actions are mostly user events such as inputs, backend data pushes or even scheduled events.
To better understand Actions, let’s look at an example from the MobX documentation.
class Ticker { @observable tick = 0 @action increment() { this.tick++ // 'this' will always be correct } } const ticker = new Ticker() setInterval(ticker.increment, 1000)
Here, we set an @observable tick with an initial value of 0. Next, we created a function increment that is also an action that updates the initial value once a tick is made every second.
Observables In MobX
Observables or observable values in MobX are mostly JavaScript primitives, plain objects, classes, arrays and maps. They’re mostly used by first declaring an observable and adding a value to it and then calling it by adding an @observable as shown below:
observable(value) @observable classProperty = value
Store Architecture Approach In MobX
MobX principal architecture includes parts and ideas such as services, store, view models and containers — some of which are explained below.
Service This is usually a function called from a container; they can be used to get data from APIs and be added to the store.
Store As the name implies, this is the central place of the state used by an application. Usually in MobX, these include the observables, variables, actions and computed properties.
Container This calls service and puts data from View Model to View Component as React props (should be marked with @observer decorator).
MobX In React And Native Applications
For learning purposes, in this tutorial, we are going to build a simple list app that will allow a user to add, view, and delete list items. We will be using MobX as a state manager in this application to add lists, update and delete them from the app state. However, it’s important to note that you already understand the basic concepts of JavaScript and React.
Without further ado, let’s start!
Setting Up Your Environment
Now that we know how what MobX is and how it works, let me walk you through setting up your project.
First, let’s create a project with the following, write the following code on your terminal to initialise a project:
npx create-react-app listapp
The above code will create a bare React application using the create-react-app package. Move into the project directory:
cd listapp
For this app, we will need three components:
TitleInput This will contain the title for our project and an input form for adding lists.
List This will be an input form that would allow a user to add a list. It will have an add button to add our list items.
ListsDisplay This component will display all of the user list items and also a delete button that’s automatically generated when a user adds a list item.
We will use a Store.js to contain the app state and methods to modify it similar to RedUX. Let’s outline what they will be used for.
mobx This is the state manager we will be using for this project.
mobx-react This is the official React bindings for MobX.
bootstrap We will be using bootstrap version 4.5 to style our project.
uuid This is used to automatically create keys for deleting lists.
Having done that, let’s go ahead and install these packages. I will be installing them with an npm alternative done in yarn:
yarn add mobx mobx-react [email protected] uuid
Once the packages are installed, we will start our app in development mode by running the code below in our terminal:
yarn start
Setting Up Our App Store
Let’s create a store for our project. First, create a file in the root directory of our project called ListStore, this will be the central location of our app state.
For this app, we will need to create a ListStore in order not to repeat ourselves when we use it in other app components.
/*** src/Store.js ***/ import { observable, action, computed } from "mobx"; import { v4 } from "uuid"; export class List { @observable value @observable done constructor (value) { this.id = v4() this.value = value } } export class ListStore { @observable lists = [] @observable filter = "" @action addList = (value) => { this.lists.push(new List(value)) } @action deleteList = (list) => { this.lists = this.lists.filter(t => t !== list) } @computed get filteredLists () { const matchCase = new RegExp(this.filter, "i") return this.lists.filter(list=> !this.filter || matchCase.test(list.value)) } }
In the code above, we imported three functions from mobx.
observable This holds a variable which can be updated in the event of a change in state.
action Used to modify the application state.
computed Values that can be derived from the existing state or other computed values, it changes after a state gets modified.
The class List has two object values which are done and value which will hold the initial state of the app and the modification in the case of changes.
We want our new list to automatically create a key so that we can automatically get a delete button once a list is created, Here uuid is used to automatically create keys in our application.
Next, we added an addList function that will add lists when clicked by using the .push() method to push the list in the array we already created in the @observable lists array.
The deleteList function accepts List as a property which is supposed to be the item the user wants to remove. Then we set the value of this.Lists to a new array after we have removed the selected item.
Both addLists and deleteList are actions because they modify the state of our app when changes are made.
Initializing The MobX Store
Next on our list is to import our store in our App.js and use it in our project.
import React from 'react'; import Navbar from "./components/navbar"; import ListDisplay from "./components/ListDisplay"; import {ListStore} from './ListStore'; function App() { const store = new ListStore() return ( <div> <Navbar store={store}/> <ListDisplay store={store}/> </div> ); } export default App;
Here we imported the TitleInput and ListDisplay components. Then we initialized the store in our App.js in order to be able to pass it as props to the TitleInput and ListDisplay components.
Normally this will throw an error because we’ve not worked on the other components, so let’s do that. Let’s build out the ListDisplay component.
ListDisplay
This component displays all of our added lists and also automatically generates a delete button once a new list is added.
import React from 'react' import List from "./List"; import { observer } from 'mobx-react'; function ListDisplay(props) { const { deleteList, filteredLists } = props.store return ( <div> <div className="container"> {filteredLists.map(list => ( <List key={list.id} list={list} deleteList={deleteList} /> ))} </div> </div> ) } export default observer(ListDisplay)
For this component, we created a function ListDisplay and made it an observer, we also destructure the list and deletelist functions from the store, by doing this, we made it easier to pass then as object props.
Next, we map through filteredLists to return the lists, which we then use in building the individual list by passing the returned item as props to the List component.
Once done, our component should look like this with lists added:
Lists displayed by `ListDisplay` component. (Large preview)
Next is to add a List and TitleInput components.
List Component
Just like our other components, our List component will export the list as an observer in order to help the store watch it for changes.
import React from 'react' import { observer } from 'mobx-react' function List(props) { return ( <div className="card"> <div className="card-body"> <div className="d-flex justify-content-between align-items-center"> <p className={`title ${props.list.done ? "text-secondary" : ""}`}> {props.list.value} </p> <div> <button onClick={props.deleteList.bind(this, props.list)} className="btn btn-danger font-weight-bold py-2 px-5 ml-2"> Delete </button> </div> </div> </div> </div> ) } export default observer(List)
I used the bootstrap to create cards in the first set of divs and also align the delete icon to move towards the right-hand side of the app. First, we created a card component to handle our list and then we created a button tag for the delete button that will accept two objects of this and pass a prop to the list, this will on click, will remove the selected list item from the lists in the page.
A single list component with the delete button. (Large preview)
Next is to our TitleInput which will contain our input form for adding lists and the title for the project.
TitleInput
Similar to our other projects, we will be adding an @observer function so that the component will be able to accept props from the app Store.
import React, { useState } from 'react' import { observer } from 'mobx-react' function Navbar(props) { const [value, setValue] = useState("") const {addList} = props.store const prepareAddList = (e) => { e.preventDefault() addList(value) setValue("") } return ( <div className="container mt-3"> <h1 className="title">List App</h1> <form onSubmit={prepareAddList} className="form-group"> <div className="row ml-lg-2"> <input className="form-control-lg col-12 col-lg-9 col-sm-12 mr-3 border border-secondary" value={value} type="text" onChange={(e) => setValue(e.target.value)} placeholder="Enter list" /> <button className="col-lg-2 col-5 col-sm-5 mt-2 mt-lg-0 mt-sm-2 btn btn-lg btn-success font-weight-bold"> Add to List </button> </div> </form> </div> ) } export default observer(Navbar)
First, we initialized an initial state. Using React Hooks, we added an initial state called values which we set to an empty string. We use this to hold the value of what is entered in the input field. To know more about React Hooks, you can check out this article by David Abiodun.
Then we called an object for adding lists to the store addList and passed it as props from the app store.
Next we created a function preparedAddList to accept an event object for the input forms, we also added a button for adding the lists manually on click.
Almost done, we need to restart our project server by running:
yarn start
And our TitleInput should look like this:
Title and input component. (Large preview)
We are now done with all of our app components, so let’s assemble it in our App.js. To do that, we need to import our components titleInput and ListDisplay. We also need to import our store from the Store component.
In order for MobX to work in our App, we need to pass the MobX store as props in our App and individual components so that they get the properties and functions in the store.
import React from 'react'; import Navbar from "./components/navbar"; import ListDisplay from "./components/ListDisplay"; import {ListStore} from './ListStore'; function App() { const store = new ListStore() return ( <div> <Navbar store={store}/> <ListDisplay store={store}/> </div> ); } export default App;
Our app should look like this when completed:
(Large preview)
Conclusion
MobX is a great state manager especially for React-based applications, building our list app, we’ve learned the basic concepts of MobX, state, derivations, and actions. A working version of this app can be found here:
You can take this further by using MobX in the next application you build that involves the management of state. I’d love to see what new things you come up with. You can read more on MobX and state management applications in the references below.
Resources And References
(ks, ra, yk, il)
Website Design & SEO Delray Beach by DBL07.co
Delray Beach SEO
source http://www.scpie.org/using-mobx-as-a-state-manager-in-react-native-applications/ source https://scpie.tumblr.com/post/627585998992343040
0 notes
Text
Using Mobx As A State Manager In React Native Applications
About The Author
Fortune Ikechi is a Frontend Engineer based in Rivers State Nigeria. He is a student of the University of Port-Harcourt. He is passionate about community and … More about Fortune …
MobX is one of the many state management tools available to React developers. In this tutorial, Fortune Kay explains what MobX is and how you can use it in your React applications by building one from scratch.
State management is an integral part of developing JavaScript applications especially React and React Native applications. In this tutorial, we are going to learn how to use the MobX library for state management; understand the core concepts, some use cases and build a simple example.
Note: Basic knowledge of Javascript and React Native will be of great benefit as you work through this tutorial.
Using MobX In React Applications
State is the data that your component(s) is working with — it holds the data that a component requires and it dictates what a component renders. State management is the process of managing how the state gets updated and passed from one component to another. Monitoring and working with data in an application can be difficult and that’s the need for state management libraries. Handling all the data for your application can be a little daunting especially when your application grows in size and complexity, building your own state management tool is not just time-consuming but difficult, This is why you might want to use a state management library.
However, it is important to know that state isn’t the only data that a component renders, components can also render props passed down to it.
Options For State Management
State management libraries for React Native applications include; React Context API, Redux, MobX and Unstated Next.
Although these state managers each have their advantages and disadvantages, I personally recommend MobX because of its simplicity, minimal boilerplate code — it doesn’t require you change your code, this is because in its core, MobX is and looks like JavaScript; you don’t need a change of architecture to support it (unlike RedUX and to a lesser extent Context).
In fact it’s such an invisible abstraction that in many cases if you take out all of the MobX code — the @observable, @computed, @action and observer decorators, your code will work exactly the same (though it’ll have some performance issues) and it’s not limited to a global state. These are some reasons to go forward with MobX as a state manager of choice for your React Native applications.
Although it’s also important to note some issues with using MobX as a state manager, some of which include its avoidance of rules on how to implement it and MobX can be difficult to debug especially when you change state directly in a component without using the @actions parameter.
What Is MobX?
According to the official documentation, MobX is a battle-tested library that makes state management simple and scalable by transparently applying functional reactive programming. MobX treats your application like a spreadsheet. The logic is that Anything that can be derived from the application state, should be done automatically.
MobX state architecture. (Large preview)
Core Principles And Concept Of MobX
MobX differentiates itself from other state managers with the following concepts.
1. State
State is the data your application holds — it’s roughly the entire contents of its memory. This also applies to your components.
2. Derivations
In MobX, anything that can be derived from the state without interactions is a derivation. Examples of derivations include:
User interface,
Backend add-ons such as changes to a server.
MobX has two mains types of derivations:
Computed values Computed values are mostly values that can be derived from a current state using pure functions.
Reactions Reactions in derivations are side effects that happen as a results of changes in your application state. They are similar to a computed value, but instead of producing a new value, a reaction produces a side effect for things like printing to the console, making network requests, incrementally updating the React component tree to patch the DOM, and so on.
A golden rule when using MobX is that when creating a value based on the current state, use a computed value.
3. Actions
Unlike derivations, actions are code that cause changes to an application state — code that changes the state. They are anything that modifies the state. With MobX you can make it explicit in your code, Actions are mostly user events such as inputs, backend data pushes or even scheduled events.
To better understand Actions, let’s look at an example from the MobX documentation.
class Ticker { @observable tick = 0 @action increment() { this.tick++ // 'this' will always be correct } } const ticker = new Ticker() setInterval(ticker.increment, 1000)
Here, we set an @observable tick with an initial value of 0. Next, we created a function increment that is also an action that updates the initial value once a tick is made every second.
Observables In MobX
Observables or observable values in MobX are mostly JavaScript primitives, plain objects, classes, arrays and maps. They’re mostly used by first declaring an observable and adding a value to it and then calling it by adding an @observable as shown below:
observable(value) @observable classProperty = value
Store Architecture Approach In MobX
MobX principal architecture includes parts and ideas such as services, store, view models and containers — some of which are explained below.
Service This is usually a function called from a container; they can be used to get data from APIs and be added to the store.
Store As the name implies, this is the central place of the state used by an application. Usually in MobX, these include the observables, variables, actions and computed properties.
Container This calls service and puts data from View Model to View Component as React props (should be marked with @observer decorator).
MobX In React And Native Applications
For learning purposes, in this tutorial, we are going to build a simple list app that will allow a user to add, view, and delete list items. We will be using MobX as a state manager in this application to add lists, update and delete them from the app state. However, it’s important to note that you already understand the basic concepts of JavaScript and React.
Without further ado, let’s start!
Setting Up Your Environment
Now that we know how what MobX is and how it works, let me walk you through setting up your project.
First, let’s create a project with the following, write the following code on your terminal to initialise a project:
npx create-react-app listapp
The above code will create a bare React application using the create-react-app package. Move into the project directory:
cd listapp
For this app, we will need three components:
TitleInput This will contain the title for our project and an input form for adding lists.
List This will be an input form that would allow a user to add a list. It will have an add button to add our list items.
ListsDisplay This component will display all of the user list items and also a delete button that’s automatically generated when a user adds a list item.
We will use a Store.js to contain the app state and methods to modify it similar to RedUX. Let’s outline what they will be used for.
mobx This is the state manager we will be using for this project.
mobx-react This is the official React bindings for MobX.
bootstrap We will be using bootstrap version 4.5 to style our project.
uuid This is used to automatically create keys for deleting lists.
Having done that, let’s go ahead and install these packages. I will be installing them with an npm alternative done in yarn:
yarn add mobx mobx-react [email protected] uuid
Once the packages are installed, we will start our app in development mode by running the code below in our terminal:
yarn start
Setting Up Our App Store
Let’s create a store for our project. First, create a file in the root directory of our project called ListStore, this will be the central location of our app state.
For this app, we will need to create a ListStore in order not to repeat ourselves when we use it in other app components.
/*** src/Store.js ***/ import { observable, action, computed } from "mobx"; import { v4 } from "uuid"; export class List { @observable value @observable done constructor (value) { this.id = v4() this.value = value } } export class ListStore { @observable lists = [] @observable filter = "" @action addList = (value) => { this.lists.push(new List(value)) } @action deleteList = (list) => { this.lists = this.lists.filter(t => t !== list) } @computed get filteredLists () { const matchCase = new RegExp(this.filter, "i") return this.lists.filter(list=> !this.filter || matchCase.test(list.value)) } }
In the code above, we imported three functions from mobx.
observable This holds a variable which can be updated in the event of a change in state.
action Used to modify the application state.
computed Values that can be derived from the existing state or other computed values, it changes after a state gets modified.
The class List has two object values which are done and value which will hold the initial state of the app and the modification in the case of changes.
We want our new list to automatically create a key so that we can automatically get a delete button once a list is created, Here uuid is used to automatically create keys in our application.
Next, we added an addList function that will add lists when clicked by using the .push() method to push the list in the array we already created in the @observable lists array.
The deleteList function accepts List as a property which is supposed to be the item the user wants to remove. Then we set the value of this.Lists to a new array after we have removed the selected item.
Both addLists and deleteList are actions because they modify the state of our app when changes are made.
Initializing The MobX Store
Next on our list is to import our store in our App.js and use it in our project.
import React from 'react'; import Navbar from "./components/navbar"; import ListDisplay from "./components/ListDisplay"; import {ListStore} from './ListStore'; function App() { const store = new ListStore() return ( <div> <Navbar store={store}/> <ListDisplay store={store}/> </div> ); } export default App;
Here we imported the TitleInput and ListDisplay components. Then we initialized the store in our App.js in order to be able to pass it as props to the TitleInput and ListDisplay components.
Normally this will throw an error because we’ve not worked on the other components, so let’s do that. Let’s build out the ListDisplay component.
ListDisplay
This component displays all of our added lists and also automatically generates a delete button once a new list is added.
import React from 'react' import List from "./List"; import { observer } from 'mobx-react'; function ListDisplay(props) { const { deleteList, filteredLists } = props.store return ( <div> <div className="container"> {filteredLists.map(list => ( <List key={list.id} list={list} deleteList={deleteList} /> ))} </div> </div> ) } export default observer(ListDisplay)
For this component, we created a function ListDisplay and made it an observer, we also destructure the list and deletelist functions from the store, by doing this, we made it easier to pass then as object props.
Next, we map through filteredLists to return the lists, which we then use in building the individual list by passing the returned item as props to the List component.
Once done, our component should look like this with lists added:
Lists displayed by `ListDisplay` component. (Large preview)
Next is to add a List and TitleInput components.
List Component
Just like our other components, our List component will export the list as an observer in order to help the store watch it for changes.
import React from 'react' import { observer } from 'mobx-react' function List(props) { return ( <div className="card"> <div className="card-body"> <div className="d-flex justify-content-between align-items-center"> <p className={`title ${props.list.done ? "text-secondary" : ""}`}> {props.list.value} </p> <div> <button onClick={props.deleteList.bind(this, props.list)} className="btn btn-danger font-weight-bold py-2 px-5 ml-2"> Delete </button> </div> </div> </div> </div> ) } export default observer(List)
I used the bootstrap to create cards in the first set of divs and also align the delete icon to move towards the right-hand side of the app. First, we created a card component to handle our list and then we created a button tag for the delete button that will accept two objects of this and pass a prop to the list, this will on click, will remove the selected list item from the lists in the page.
A single list component with the delete button. (Large preview)
Next is to our TitleInput which will contain our input form for adding lists and the title for the project.
TitleInput
Similar to our other projects, we will be adding an @observer function so that the component will be able to accept props from the app Store.
import React, { useState } from 'react' import { observer } from 'mobx-react' function Navbar(props) { const [value, setValue] = useState("") const {addList} = props.store const prepareAddList = (e) => { e.preventDefault() addList(value) setValue("") } return ( <div className="container mt-3"> <h1 className="title">List App</h1> <form onSubmit={prepareAddList} className="form-group"> <div className="row ml-lg-2"> <input className="form-control-lg col-12 col-lg-9 col-sm-12 mr-3 border border-secondary" value={value} type="text" onChange={(e) => setValue(e.target.value)} placeholder="Enter list" /> <button className="col-lg-2 col-5 col-sm-5 mt-2 mt-lg-0 mt-sm-2 btn btn-lg btn-success font-weight-bold"> Add to List </button> </div> </form> </div> ) } export default observer(Navbar)
First, we initialized an initial state. Using React Hooks, we added an initial state called values which we set to an empty string. We use this to hold the value of what is entered in the input field. To know more about React Hooks, you can check out this article by David Abiodun.
Then we called an object for adding lists to the store addList and passed it as props from the app store.
Next we created a function preparedAddList to accept an event object for the input forms, we also added a button for adding the lists manually on click.
Almost done, we need to restart our project server by running:
yarn start
And our TitleInput should look like this:
Title and input component. (Large preview)
We are now done with all of our app components, so let’s assemble it in our App.js. To do that, we need to import our components titleInput and ListDisplay. We also need to import our store from the Store component.
In order for MobX to work in our App, we need to pass the MobX store as props in our App and individual components so that they get the properties and functions in the store.
import React from 'react'; import Navbar from "./components/navbar"; import ListDisplay from "./components/ListDisplay"; import {ListStore} from './ListStore'; function App() { const store = new ListStore() return ( <div> <Navbar store={store}/> <ListDisplay store={store}/> </div> ); } export default App;
Our app should look like this when completed:
(Large preview)
Conclusion
MobX is a great state manager especially for React-based applications, building our list app, we’ve learned the basic concepts of MobX, state, derivations, and actions. A working version of this app can be found here:
You can take this further by using MobX in the next application you build that involves the management of state. I’d love to see what new things you come up with. You can read more on MobX and state management applications in the references below.
Resources And References
(ks, ra, yk, il)
Website Design & SEO Delray Beach by DBL07.co
Delray Beach SEO
source http://www.scpie.org/using-mobx-as-a-state-manager-in-react-native-applications/
0 notes
Text
CEN3031 Creating a server-side CRUD module using Express Solved
In Bootcamp Assignment #1, we created a simple node server that retrieved our listings by responding to GET requests to '/listings'. You are now going to add more functionality to this server that allows us to create, read, update, and delete listings from a Mongo database. These tasks are commonly referred to as CRUD.
Introduction to Express
While these new requests could be handled in the same fashion as the original request handler, it would quickly become unweildly. There would need to be many conditional statements to handle requests to the different URL paths and different HTTP methods (such as POST, PUT, and DELETE). Luckily, the Express library makes this task much simpler by providing a layer of abstraction for handling HTTP requests in a Node server. To provide an example, here is the request handler we wrote in assignment 1: var requestHandler = function(request, response) { var parsedUrl = url.parse(request.url); if(request.method === 'GET') { if(parsedUrl.path === '/listings') { response.writeHead(200, { 'Content-Type': 'application/json' }); response.end(JSON.stringify(listingData)); } else { response.writeHead(404); response.end('Bad gateway error'); } } else { response.writeHead(404); response.end('Bad gateway error'); } }; Now here is the same request handler written using Express: app.get('/listings', function(req, res) { res.send(listingData); }); app.all('/*', function(req, res) { res.status(404).send('Bad gateway error'); });
Middleware
Understanding the concept of middleware is extremely important in using Express effectively. Middleware allows you to invoke functions on a request before it reaches its final request handler. As a simple (yet quite useless) example, let's add a greeting to each request made to the server. app.use(function(req, res, next) { req.greeting = 'Hello there!'; next(); }); app.get('/', function(req, res) { res.send(req.greeting); }); In addition to the usual request and response objects, we now pass an additional object called next. Invoking next will pass the request on to whatever function is next in line to handle it. Now, let's say the application we are building has users with administrative privledges. There will be certain routes that we want to make sure the user has the correct privledges before allowing the request to be handled. Using express, this becomes a relatively simple task: var checkPermissions = function(req, res, next) { if(req.isAdmin === true) { next(); } else { res.status(400).send('User does not have permission to access this path'); } }; app.get('/privateData', checkPermissions, function(req, res) { res.send('Some really critical information'); }); The checkPermissions function serves as middleware that is invoked before passing the request to its final destination. A final note: order matters when using middleware. If you place app.use() after a request handler, that middleware will not be invoked. Keep this in mind when developing your applications in case you encounter bugs.
Assignment Details
Now go ahead and clone this assignment's repository. You'll notice that the file structure of the application is now more involved than previous assignments. Browse around and take note of where each part of the application exists. Navigate to server/config/express.js. This is where you will place code to configure your Express application. The morgan module is used to log requests to the console for debugging purposes. The body parser module is middleware that will allow you to access any data sent in requests as req.body. In server/routes/listings.server.routes.js, you will find code that specifies the request handlers for CRUD tasks. To learn more about the Express router, go to this page and scroll down to the section on express.Router.
Assignment Submission
Implement the request handlers in listings.server.controller.js test your implementation by running the tests found in listings.server.routes.test.js Complete the app configuration in express.js. serve the static files found in the public folder when a user makes a request to the path /. Refer to this documentation for help use the listings router for requests going to the /api/listings path direct users to the client side index.html file for requests to any other path Implement client-side addListing and deleteListing functions in listingController.js. Implement delete function in listingFactory.js. Copy or improve any styling you added in Bootcamp Assignment #2. Make sure your server is functioning correctly by starting with the command: node server.js Check your user interface: http://localhost:8080/. Read the full article
0 notes
Text
i think a lot of them have splintered off by now but back when there was more of a fandom i dont think i fucked w a lot of squip stans bc either they were squipjer shippers or they mostly liked the squip under redemption arc pretenses. i think the squip should be a huge bitch and very scary forever
#myposts#deletelist#i liked a lot of the squip fan lore but there was a lot goin' on and i fell off of it#😅and....... wellll 😅 i just like canon squip 😅😅#ahaha 😅😊 i chalk most of my disconnect from the fandom up to the fact that i like bmc bc its a mix of both the human stuff and sci fi stuff#where i think most people prefer one or the other. that and i just dont give a fuck about shipping#i dont knowww#i feel like if i just wanted to see teens in romance drama or i just wanted to see elaborate sci fi lore id just. watch a different show ?#i do like both but i prefer when theyre intertwined..... which is why i liked bmc so much in the first place#im not even being a hater in fact typing this up reminded me i wanted to go backread some squip askblogs#just idk#idk i dont knoww i wish more people made the type of bmc content i like#the way i see bmc isnt even super unique or anything i guess most people have just moved on? i dont knowwwwww
0 notes
Text
wall-e discussion on my twt tl and when the captain is yelling at the axiom and says i dont want to survive i want to live... robots amiright
#myposts#deletelist#who up thinking about ai#i havent cared for wall e since i was forced to watch it for like the 8th time in elementary school but its awesome and relevant forever#sighs........
0 notes