问:
Java Delegates?
Does the Java language have delegate features, similar to how C# has support for delegates?</p>

答:
The code described  offers many of the advantages of C# delegates. Methods, either static or dynamic, can be treated in a uniform manner. The complexity in calling methods through reflection is reduced and the code is reusable, in the sense of requiring no additional classes in the user code. Note we are calling an alternate convenience version of invoke, where a method with one parameter can be called without creating an object array.Java code below:</p>

```<code>  class Class1 {
        public void show(String s) { System.out.println(s); }
    }

    class Class2 {
        public void display(String s) { System.out.println(s); }
    }

    // allows static method as well
    class Class3 {
        public static void staticDisplay(String s) { System.out.println(s); }
    }

    public class TestDelegate  {
        public static final Class[] OUTPUT_ARGS = { String.class };
        public final Delegator DO_SHOW = new Delegator(OUTPUT_ARGS,Void.TYPE);

        public void main(String[] args)  {
            Delegate[] items = new Delegate[3];

            items[0] = DO_SHOW .build(new Class1(),"show,);
            items[1] = DO_SHOW.build (new Class2(),"display");
            items[2] = DO_SHOW.build(Class3.class, "staticDisplay");

            for(int i = 0; i < items.length; i++) {
                items[i].invoke("Hello World");
            }
        }
    }
</code>```

OwnerDisplayName: Mark

ContentLicense: CC BY-SA 2.5

Title: Java Delegates?

Body:
The code described  offers many of the advantages of C# delegates. Methods, either static or dynamic, can be treated in a uniform manner. The complexity in calling methods through reflection is reduced and the code is reusable, in the sense of requiring no additional classes in the user code. Note we are calling an alternate convenience version of invoke, where a method with one parameter can be called without creating an object array.Java code below:

  class Class1 {
        public void show(String s) { System.out.println(s); }
    }

    class Class2 {
        public void display(String s) { System.out.println(s); }
    }

    // allows static method as well
    class Class3 {
        public static void staticDisplay(String s) { System.out.println(s); }
    }

    public class TestDelegate  {
        public static final Class[] OUTPUT_ARGS = { String.class };
        public final Delegator DO_SHOW = new Delegator(OUTPUT_ARGS,Void.TYPE);

        public void main(String[] args)  {
            Delegate[] items = new Delegate[3];

            items[0] = DO_SHOW .build(new Class1(),"show,);
            items[1] = DO_SHOW.build (new Class2(),"display");
            items[2] = DO_SHOW.build(Class3.class, "staticDisplay");

            for(int i = 0; i < items.length; i++) {
                items[i].invoke("Hello World");
            }
        }
    }


来源: stackexchange

问:
Why is my service not updating on my app component?
I am working with Ionic 4 and I want to show information about the current logged user but is not working I mean it works on any component except the app component, I am using a variable called userData which is a BehaviorSubject. Do you know what is wrong with my code?

auth.service.ts

```<code>import { Platform } from '@ionic/angular';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { BehaviorSubject, Observable, from, of, throwError } from 'rxjs';
import { take, map,tap, switchMap, catchError } from 'rxjs/operators';
import { JwtHelperService } from "@auth0/angular-jwt";
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { Tokens } from '../models/tokens';
import { environment } from 'src/environments/environment';

const helper = new JwtHelperService();
//Agregar token access y refresh
const accessToken = 'access';
const refreshToken = 'refresh';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  public user: Observable<any>;
  private userData = new BehaviorSubject(null);
  private access: string = null;
  private refresh: string = null;
  constructor(private storage: Storage, private http: HttpClient, private plt: Platform, private router: Router) {
    this.loadStoredTokens();
  }

  getTokenExpirationDate(userData): Date {
    if (userData['exp'] === undefined) return null;

    const date = new Date(0);
    date.setUTCSeconds(userData['exp']);
    return date;
  }

  isAcessTokenExpired(): boolean {
    let userData = this.userData.getValue();
    console.log(userData);
    if(!userData) return true;

    const date = this.getTokenExpirationDate(userData);
    if(date === undefined) return false;
    return !(date.valueOf() > new Date().valueOf());
  }

  loadStoredTokens() {
    let platformObs = from(this.plt.ready());

    this.user = platformObs.pipe(
      switchMap(() => {
        return from(this.storage.get(refreshToken));
      }),
      map(refreshToken => {
        if (refreshToken) {
          this.refresh = refreshToken;
        } else {
          this.refresh = null;
        }
      }),
      switchMap(() => {
        return from(this.storage.get(accessToken));
      }),
      map(accessToken => {
        if (accessToken) {
          this.access = accessToken;
          let decoded = helper.decodeToken(accessToken);
          this.userData.next(decoded);
          return true;
        } else {
          this.access = null;
          return null;
        }
      })
    );

  }

  login(credentials: {username: string, password: string }) {
    return this.http
    .post(`${environment.apiUrl}/token/obtain/`,credentials)
    .pipe(
      take(1),
      map(res => {
        // Extract the JWT
        return res;
      }),
      switchMap(token => {
        let decoded = helper.decodeToken(token['access']);
        this.userData.next(decoded);

        from(this.storage.set(refreshToken, token['refresh']))
        let storageObs = from(this.storage.set(accessToken, token['access']));
        return storageObs;
      })
    );

  }

  getUser() {
    return this.userData.getValue();
  }

  logout() {
    this.storage.remove(accessToken).then(() => {

      this.storage.remove(refreshToken).then(() => {
        this.router.navigateByUrl('/');
        this.userData.next(null);
      });

    });
  }

getAccessToken() {
  return  this.access;
}

 getRefreshToken() {
  return this.refresh;
}

setAccessToken(token) {
  this.storage.set(accessToken, token);
}

  refreshToken() {
    return this.http.post<any>(`${environment.apiUrl}/token/refresh/`, {
    'refresh': this.getRefreshToken()
    }).pipe(tap((tokens: Tokens) => {
      this.setAccessToken(tokens.access);
      this.access = tokens.access;
    }));
  }
}
</code>```

app.component.ts (I am using getUser() function in order to get the current user information)

```<code>import { Component, OnInit, ViewChildren, QueryList, OnChanges } from '@angular/core';

import { Platform, ModalController, ActionSheetController, PopoverController, IonRouterOutlet, MenuController } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { Router } from '@angular/router';
import { faHome, faInfo, faFileContract } from '@fortawesome/free-solid-svg-icons';
import { ToastController } from '@ionic/angular';
import { AuthService } from './auth/services/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent implements OnInit {
  public selectedIndex = 0;
  user = null;

  public appPages = [
    {
      title: 'Home',
      url: '/home',
      icon: faHome
    },
    {
      title: 'About',
      url: '/about',
      icon: faInfo
    },
    {
      title: 'Legal',
      url: '/legal',
      icon: faFileContract
    }
  ];

  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    public modalCtrl: ModalController,
    private menu: MenuController,
    private actionSheetCtrl: ActionSheetController,
    private popoverCtrl: PopoverController,
    private router: Router,
    public toastController: ToastController,
    private auth: AuthService
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.backgroundColorByHexString('#D4AF37');
      this.splashScreen.hide();
    });
  }

  ngOnInit() {

    this.user = this.auth.getUser();
    const path = window.location.pathname.split('home/')[1];
    if (path !== undefined) {
      this.selectedIndex = this.appPages.findIndex(page => page.title.toLowerCase() === path.toLowerCase());
    }

  }

}
</code>```

app.component.html (here I want to show the user information, the same code is working in every component except this)

```<code><ion-app>
  <ion-split-pane contentId="main-content">
    <ion-menu contentId="main-content" type="overlay">
      <ion-content>
        <ion-list id="inbox-list">
          <ion-list-header>Menu</ion-list-header>
          <ion-note *ngIf="user">{{ user.email }} </ion-note>

          <ion-menu-toggle auto-hide="false" *ngFor="let p of appPages; let i = index">
            <ion-item (click)="selectedIndex = i" routerDirection="root" [routerLink]="[p.url]" lines="none" detail="false" [class.selected]="selectedIndex == i">
              <fa-icon (keyup)="onKeyFaIcon($event)" slot="start" [icon]="p.icon"></fa-icon>

              <ion-label>{{ p.title }}</ion-label>
            </ion-item>
          </ion-menu-toggle>
        </ion-list>

      </ion-content>
    </ion-menu>
    <ion-router-outlet id="main-content"></ion-router-outlet>
  </ion-split-pane>
</ion-app>
</code>```

答:
Because BehaviorSubject is async and you need to subscribe to it.

ngOnInit() {
  this.auth.getUser().subscribe(user => this.user = user);
}
```

<p>Also keep in mind that it's not instant and all dependencies on <code>this.user</code> should be async too.</p>

<p>For example in template you can check</p>

<pre class="lang-html prettyprint-override"><code><ng-container *ngIf="user">
  {{ user }} now we can use it
</ng-container>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working with Ionic 4 and I want to show information about the current logged user but is not working I mean it works on any component except the app component, I am using a variable called userData which is a BehaviorSubject. Do you know what is wrong with my code?

auth.service.ts

import { Platform } from '@ionic/angular';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { BehaviorSubject, Observable, from, of, throwError } from 'rxjs';
import { take, map,tap, switchMap, catchError } from 'rxjs/operators';
import { JwtHelperService } from "@auth0/angular-jwt";
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { Tokens } from '../models/tokens';
import { environment } from 'src/environments/environment';

const helper = new JwtHelperService();
//Agregar token access y refresh
const accessToken = 'access';
const refreshToken = 'refresh';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  public user: Observable<any>;
  private userData = new BehaviorSubject(null);
  private access: string = null;
  private refresh: string = null;
  constructor(private storage: Storage, private http: HttpClient, private plt: Platform, private router: Router) {
    this.loadStoredTokens();
  }

  getTokenExpirationDate(userData): Date {
    if (userData['exp'] === undefined) return null;

    const date = new Date(0);
    date.setUTCSeconds(userData['exp']);
    return date;
  }

  isAcessTokenExpired(): boolean {
    let userData = this.userData.getValue();
    console.log(userData);
    if(!userData) return true;

    const date = this.getTokenExpirationDate(userData);
    if(date === undefined) return false;
    return !(date.valueOf() > new Date().valueOf());
  }

  loadStoredTokens() {
    let platformObs = from(this.plt.ready());

    this.user = platformObs.pipe(
      switchMap(() => {
        return from(this.storage.get(refreshToken));
      }),
      map(refreshToken => {
        if (refreshToken) {
          this.refresh = refreshToken;
        } else {
          this.refresh = null;
        }
      }),
      switchMap(() => {
        return from(this.storage.get(accessToken));
      }),
      map(accessToken => {
        if (accessToken) {
          this.access = accessToken;
          let decoded = helper.decodeToken(accessToken);
          this.userData.next(decoded);
          return true;
        } else {
          this.access = null;
          return null;
        }
      })
    );

  }

  login(credentials: {username: string, password: string }) {
    return this.http
    .post(`${environment.apiUrl}/token/obtain/`,credentials)
    .pipe(
      take(1),
      map(res => {
        // Extract the JWT
        return res;
      }),
      switchMap(token => {
        let decoded = helper.decodeToken(token['access']);
        this.userData.next(decoded);

        from(this.storage.set(refreshToken, token['refresh']))
        let storageObs = from(this.storage.set(accessToken, token['access']));
        return storageObs;
      })
    );

  }

  getUser() {
    return this.userData.getValue();
  }

  logout() {
    this.storage.remove(accessToken).then(() => {

      this.storage.remove(refreshToken).then(() => {
        this.router.navigateByUrl('/');
        this.userData.next(null);
      });

    });
  }

getAccessToken() {
  return  this.access;
}

 getRefreshToken() {
  return this.refresh;
}

setAccessToken(token) {
  this.storage.set(accessToken, token);
}

  refreshToken() {
    return this.http.post<any>(`${environment.apiUrl}/token/refresh/`, {
    'refresh': this.getRefreshToken()
    }).pipe(tap((tokens: Tokens) => {
      this.setAccessToken(tokens.access);
      this.access = tokens.access;
    }));
  }
}

app.component.ts (I am using getUser() function in order to get the current user information)

import { Component, OnInit, ViewChildren, QueryList, OnChanges } from '@angular/core';

import { Platform, ModalController, ActionSheetController, PopoverController, IonRouterOutlet, MenuController } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { Router } from '@angular/router';
import { faHome, faInfo, faFileContract } from '@fortawesome/free-solid-svg-icons';
import { ToastController } from '@ionic/angular';
import { AuthService } from './auth/services/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent implements OnInit {
  public selectedIndex = 0;
  user = null;

  public appPages = [
    {
      title: 'Home',
      url: '/home',
      icon: faHome
    },
    {
      title: 'About',
      url: '/about',
      icon: faInfo
    },
    {
      title: 'Legal',
      url: '/legal',
      icon: faFileContract
    }
  ];

  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    public modalCtrl: ModalController,
    private menu: MenuController,
    private actionSheetCtrl: ActionSheetController,
    private popoverCtrl: PopoverController,
    private router: Router,
    public toastController: ToastController,
    private auth: AuthService
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.backgroundColorByHexString('#D4AF37');
      this.splashScreen.hide();
    });
  }

  ngOnInit() {

    this.user = this.auth.getUser();
    const path = window.location.pathname.split('home/')[1];
    if (path !== undefined) {
      this.selectedIndex = this.appPages.findIndex(page => page.title.toLowerCase() === path.toLowerCase());
    }

  }

}

app.component.html (here I want to show the user information, the same code is working in every component except this)

<ion-app>
  <ion-split-pane contentId="main-content">
    <ion-menu contentId="main-content" type="overlay">
      <ion-content>
        <ion-list id="inbox-list">
          <ion-list-header>Menu</ion-list-header>
          <ion-note *ngIf="user">{{ user.email }} </ion-note>

          <ion-menu-toggle auto-hide="false" *ngFor="let p of appPages; let i = index">
            <ion-item (click)="selectedIndex = i" routerDirection="root" [routerLink]="[p.url]" lines="none" detail="false" [class.selected]="selectedIndex == i">
              <fa-icon (keyup)="onKeyFaIcon($event)" slot="start" [icon]="p.icon"></fa-icon>

              <ion-label>{{ p.title }}</ion-label>
            </ion-item>
          </ion-menu-toggle>
        </ion-list>

      </ion-content>
    </ion-menu>
    <ion-router-outlet id="main-content"></ion-router-outlet>
  </ion-split-pane>
</ion-app>

Body:
Because BehaviorSubject is async and you need to subscribe to it.

ngOnInit() {
  this.auth.getUser().subscribe(user => this.user = user);
}

Also keep in mind that it's not instant and all dependencies on this.user should be async too.

For example in template you can check

<ng-container *ngIf="user">
  {{ user }} now we can use it
</ng-container>


问:
Can't read the value of an state which has been defined in a function
I am trying to fetch some data from an API and store one of its arrays inside the state and access it inside componentWillMount()! But when I try to the mentioned states value, I got undefined.

Here is my code:

```<code>componentWillMount() {

        this._fetchData()

************************************
        alert(this.state.openSellOffers)
************************************
    }

    _fetchData = async () => {

        let openSellOffersRes = await fetchOpenSellOffers()
        for (let sellOffer of openSellOffersRes.orders) {
            let sellObj = {
                _id: sellOffer._id,
                currencyValue: sellOffer.currencyValue,
                unitPrice: sellOffer.unitPrice,
                totalPrice: sellOffer.totalPrice,
                type: 'sell'
            }

            this.setState({
                openSellOffers: [...this.state.openSellOffers, sellObj]
            })
        }
    }

    constructor(props) {
        super(props)

        this.state = {
            IRRBalance: 0,
            BTCBalance: 0,
            openBuyOffers: [],
            openSellOffers: [],
            closedBuyOffers: [],
            closedSellOffers: []
        }
    }
</code>```

As you can see I use alert() for showing the states value. That is the point which I get undefined instead of the exact value which API responses.

How can I solve it?

Appreciates.

答:
Basically setState() works asynchronously. So you need to wait for a few nanoseconds to get the value. You can do it in 2 ways.

1. Use await

componentWillMount() {
  await this._fetchData()
  alert(this.state.openSellOffers)
}

_fetchData = async () => {
  let openSellOffersRes = await fetchOpenSellOffers()
  for (let sellOffer of openSellOffersRes.orders) {
    let sellObj = {
      _id: sellOffer._id,
      currencyValue: sellOffer.currencyValue,
      unitPrice: sellOffer.unitPrice,
      totalPrice: sellOffer.totalPrice,
      type: 'sell'
    }

    this.setState({
      openSellOffers: [...this.state.openSellOffers, sellObj]
    })
  }
  return true;
}

```

<p>**2. Use SetTimeOut **</p>

<pre class="lang-js prettyprint-override"><code>componentWillMount() {
  this._fetchData()
  setTimeout(() => {
    alert(this.state.openSellOffers)
  }, 100)
}

_fetchData = async () => {
  let openSellOffersRes = await fetchOpenSellOffers()
  for (let sellOffer of openSellOffersRes.orders) {
    let sellObj = {
      _id: sellOffer._id,
      currencyValue: sellOffer.currencyValue,
      unitPrice: sellOffer.unitPrice,
      totalPrice: sellOffer.totalPrice,
      type: 'sell'
    }

    this.setState({
      openSellOffers: [...this.state.openSellOffers, sellObj]
    })
  }
}
</code>```

Body:
I am trying to fetch some data from an API and store one of its arrays inside the state and access it inside componentWillMount()! But when I try to the mentioned states value, I got undefined.

Here is my code:

componentWillMount() {

        this._fetchData()

************************************
        alert(this.state.openSellOffers)
************************************
    }

    _fetchData = async () => {

        let openSellOffersRes = await fetchOpenSellOffers()
        for (let sellOffer of openSellOffersRes.orders) {
            let sellObj = {
                _id: sellOffer._id,
                currencyValue: sellOffer.currencyValue,
                unitPrice: sellOffer.unitPrice,
                totalPrice: sellOffer.totalPrice,
                type: 'sell'
            }

            this.setState({
                openSellOffers: [...this.state.openSellOffers, sellObj]
            })
        }
    }

    constructor(props) {
        super(props)

        this.state = {
            IRRBalance: 0,
            BTCBalance: 0,
            openBuyOffers: [],
            openSellOffers: [],
            closedBuyOffers: [],
            closedSellOffers: []
        }
    }

As you can see I use alert() for showing the states value. That is the point which I get undefined instead of the exact value which API responses.

How can I solve it?

Appreciates.

Body:
Basically setState() works asynchronously. So you need to wait for a few nanoseconds to get the value. You can do it in 2 ways.

1. Use await

componentWillMount() {
  await this._fetchData()
  alert(this.state.openSellOffers)
}

_fetchData = async () => {
  let openSellOffersRes = await fetchOpenSellOffers()
  for (let sellOffer of openSellOffersRes.orders) {
    let sellObj = {
      _id: sellOffer._id,
      currencyValue: sellOffer.currencyValue,
      unitPrice: sellOffer.unitPrice,
      totalPrice: sellOffer.totalPrice,
      type: 'sell'
    }

    this.setState({
      openSellOffers: [...this.state.openSellOffers, sellObj]
    })
  }
  return true;
}

**2. Use SetTimeOut **

componentWillMount() {
  this._fetchData()
  setTimeout(() => {
    alert(this.state.openSellOffers)
  }, 100)
}

_fetchData = async () => {
  let openSellOffersRes = await fetchOpenSellOffers()
  for (let sellOffer of openSellOffersRes.orders) {
    let sellObj = {
      _id: sellOffer._id,
      currencyValue: sellOffer.currencyValue,
      unitPrice: sellOffer.unitPrice,
      totalPrice: sellOffer.totalPrice,
      type: 'sell'
    }

    this.setState({
      openSellOffers: [...this.state.openSellOffers, sellObj]
    })
  }
}


问:
Retreiving individual values from a column with a list
I have a dataframe with the twitter username, and the list of hashtags in a particular tweet. The hashtags column maybe a single tweet, a list of tweet or an empty tweet.

```<code>screenName      hashtags
realDonaldTrump c("#1", "#2", "#2")
realDonaldTrump character(0)
realDonaldTrump #LaunchAmerica,
realDonaldTrump #GeorgeFloyd
realDonaldTrump c("#MinneapolisRiot", "#Coronavirus")
</code>```

I want to get a list of individual hashtags against a username.

答:
You can find the unique hashtags for each screenName by unlisting them.

```<code>library(dplyr)

df %>%
  group_by(screenName) %>%
  summarise(hastags  = toString(unique(unlist(hashtags))))

# screenName      hashtags
#  <chr>           <chr>
#1 realDonaldTrump #1, #2, #LaunchAmerica
</code>```

data

```<code>df <- structure(list(screenName = c("realDonaldTrump", "realDonaldTrump",
"realDonaldTrump"), hashtags = list(c("#1", "#2", "#2"), character(0),
"#LaunchAmerica")), row.names = c(NA, -3L), class = "data.frame")
</code>```

Body:
I have a dataframe with the twitter username, and the list of hashtags in a particular tweet. The hashtags column maybe a single tweet, a list of tweet or an empty tweet.

screenName      hashtags
realDonaldTrump c("#1", "#2", "#2")
realDonaldTrump character(0)
realDonaldTrump #LaunchAmerica,
realDonaldTrump #GeorgeFloyd
realDonaldTrump c("#MinneapolisRiot", "#Coronavirus")

I want to get a list of individual hashtags against a username.

Body:
You can find the unique hashtags for each screenName by unlisting them.

library(dplyr)

df %>%
  group_by(screenName) %>%
  summarise(hastags  = toString(unique(unlist(hashtags))))

# screenName      hashtags
#  <chr>           <chr>
#1 realDonaldTrump #1, #2, #LaunchAmerica

data

df <- structure(list(screenName = c("realDonaldTrump", "realDonaldTrump",
"realDonaldTrump"), hashtags = list(c("#1", "#2", "#2"), character(0),
"#LaunchAmerica")), row.names = c(NA, -3L), class = "data.frame")


问:
How to do product sorting when we search for certain product in Django?
views.py:-

```<code>def search(request):
global pro
global products
if not request.GET.get('price_filter') == '1' or request.GET.get('price_filter') == '2':
    q = request.GET.get("q")
    products = Product.objects.filter(active=True, name__icontains=q)
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
                "brands": brands,
                "title": q + " - search"}
    return render(request, "shop/home.html", context)
pro = products

if request.GET.get('price_filter') == '1':
    products = pro.order_by('price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)

elif request.GET.get('price_filter') == '2':
    products = pro.order_by('-price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)
</code>```

In HTML:-

```<code><form method='get' action='#' style="margin-top:-20px; margin-left: 8px;">
        <input class="btn btn-outline-dark" type="checkbox" value="1" name="price_filter"/>Low to High

        <input class="btn btn-outline-dark" type="checkbox" value="2" name="price_filter"/>High to Low
        <button class="btn" type="submit" value="Sort">Sort</button>
    </form>
</code>```

Using that search we I am able to sort low to high, but when I choose High to Low, it shows certain Error:-

```<code>Cannot use None as a query value
</code>```

I know this is not the right method to do this, but can please help me out with this, or guide me with the correct way to do sorting.

答:
This error is occuring for this line:

```<code>if not request.GET.get('price_filter') == '1' or request.GET.get('price_filter') == '2':
                                                ^^^
</code>```

It states that if there is no value of request.GET.get('price_filter') and there is value of request.GET.get('price_filter'). I think here it should be a not clause like this:

```<code>if not request.GET.get('price_filter') == '1' or not request.GET.get('price_filter') == '2':
                                                 ^^^
</code>```

Reason is that, there is not input field for q in your template.

Also, you can store the querystring values in variables to make this code bit cleaner:

```<code>price_filter = request.GET.get('price_filter')

if price_filter not in ["1", "2"]:
    q = request.GET.get("q")
    # rest of the code
elif price_filter == "1":
    # more code
elif price_filter == "2":
    # more code
</code>```

Body:
views.py:-

def search(request):
global pro
global products
if not request.GET.get('price_filter') == '1' or request.GET.get('price_filter') == '2':
    q = request.GET.get("q")
    products = Product.objects.filter(active=True, name__icontains=q)
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
                "brands": brands,
                "title": q + " - search"}
    return render(request, "shop/home.html", context)
pro = products

if request.GET.get('price_filter') == '1':
    products = pro.order_by('price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)

elif request.GET.get('price_filter') == '2':
    products = pro.order_by('-price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)

In HTML:-

<form method='get' action='#' style="margin-top:-20px; margin-left: 8px;">
        <input class="btn btn-outline-dark" type="checkbox" value="1" name="price_filter"/>Low to High

        <input class="btn btn-outline-dark" type="checkbox" value="2" name="price_filter"/>High to Low
        <button class="btn" type="submit" value="Sort">Sort</button>
    </form>

Using that search we I am able to sort low to high, but when I choose High to Low, it shows certain Error:-

Cannot use None as a query value

I know this is not the right method to do this, but can please help me out with this, or guide me with the correct way to do sorting.

Body:
This error is occuring for this line:

if not request.GET.get('price_filter') == '1' or request.GET.get('price_filter') == '2':
                                                ^^^

It states that if there is no value of request.GET.get('price_filter') and there is value of request.GET.get('price_filter'). I think here it should be a not clause like this:

if not request.GET.get('price_filter') == '1' or not request.GET.get('price_filter') == '2':
                                                 ^^^

Reason is that, there is not input field for q in your template.

Also, you can store the querystring values in variables to make this code bit cleaner:

price_filter = request.GET.get('price_filter')

if price_filter not in ["1", "2"]:
    q = request.GET.get("q")
    # rest of the code
elif price_filter == "1":
    # more code
elif price_filter == "2":
    # more code


问:
How To Prevent Firebase Firestore Emulator From Clearing The Database At Exit?
I'm Planning To Use Firebase - Firestore Emulators For Handling Some Huge Amount Of Data That's Coming From A Websocket.

I just need to process the data locally in realtime.

Firestore Emulator Is A great choice since it has all the features I need. But the issue is it clears the database every time the Emulator is turned off. is there any config or settings that can change this behaviour?

if it is not possible. can somebody tell me any other Approach to use firestore locally? or any other alternative to firebase that I can use locally.

答:
With the recent updates to Firebase Emulator, you use export the data when the emulator is running and import when it starts again.

To export the data

```<code>firebase emulators:export <export-directory>
</code>```

To start and import the emulator

```<code>firebase emulators:start --import <export-directory>
</code>```

Body:
With the recent updates to Firebase Emulator, you use export the data when the emulator is running and import when it starts again.

To export the data

firebase emulators:export <export-directory>

To start and import the emulator

firebase emulators:start --import <export-directory>


问:
TypeError: Cannot read property 'page' of undefined in react
I'm developing admin page of shop.
this admin page login members like that: develop, shop, seller
When I log in with develop, it shows up well. shop also shows up well, but when I log in with seller got this error: TypeError: Cannot read property 'page' of undefined in react.

anyone can help?

```<code>
export const withPagination = (selector, action) => (WrappedComponent) => {
  class __Pagination extends React.PureComponent {
    static propTypes = {
      ...baseProps
    }

    setData = (data) => {
      const last = this._data
      this._data = data
      if (!_.isEqual(data, last)) {
        this.handleFetchData(this._lastState)
      }
    }

    handleFetchData = (state) => {
      this._lastState = state
      const { page, pageSize, sorted, filtered } = state
      this.props.getListData({ page, pageSize, sorted, filtered, data: this._data })
    }

    render() {
      const { props } = this
      return (
        <WrappedComponent
          {...props}
          handleFetchData={this.handleFetchData}
          setData={this.setData}
        />
      );
    }
  }

</code>```

答:
From the snippet given and with problem statement the only possibility is -
when try with 'seller' - page property is not present in the state object when passed to handleFetchData method's parameter.

One small suggestion : while using destructuring on -
const { page, pageSize, sorted, filtered } = state

User some default values like this -
const { page = 0, pageSize = 0, sorted = false, filtered = false} = state;
This is just for example not sure about the data types.

Body:
I'm developing admin page of shop.
this admin page login members like that: develop, shop, seller
When I log in with develop, it shows up well. shop also shows up well, but when I log in with seller got this error: TypeError: Cannot read property 'page' of undefined in react.

anyone can help?

export const withPagination = (selector, action) => (WrappedComponent) => {
  class __Pagination extends React.PureComponent {
    static propTypes = {
      ...baseProps
    }

    setData = (data) => {
      const last = this._data
      this._data = data
      if (!_.isEqual(data, last)) {
        this.handleFetchData(this._lastState)
      }
    }

    handleFetchData = (state) => {
      this._lastState = state
      const { page, pageSize, sorted, filtered } = state
      this.props.getListData({ page, pageSize, sorted, filtered, data: this._data })
    }

    render() {
      const { props } = this
      return (
        <WrappedComponent
          {...props}
          handleFetchData={this.handleFetchData}
          setData={this.setData}
        />
      );
    }
  }


问:
Using async-await not returning the values
I use the following code which works! I was able to fetch the data in the spread (then) , http200

```<code>Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      const aToken = responses[0];
      const bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });
</code>```

Now I want to wrap it with async function which return two response (responses[0], responses[1] )

I’ve created this function

```<code>const FetchData = async (): Promise<{ run: string; app: string }> => {

let aToken:string;
let bToken:string;
Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      aToken = responses[0];
      bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });

// add this return
return {
    run: aToken ,
    app: bToken
};

)}
</code>```

Now I’ve created function to call it and get the tokens

```<code>async function main() {

    let val = await FetchData();
    console.log(val)

}
</code>```

The problem is that I got empty value in the val property, while put a breakpoint inside main function
I see that I got into the console, before I actually get the values from the ).then(axios.spread(( ,
Any idea how to adopt the code to return the value from the spread operator and then call to the console?

答:
```<code>const res = await Promist.all([...])
return { run: res[0], app: res[1] }
</code>```

Body:
I use the following code which works! I was able to fetch the data in the spread (then) , http200

Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      const aToken = responses[0];
      const bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });

Now I want to wrap it with async function which return two response (responses[0], responses[1] )

I’ve created this function

const FetchData = async (): Promise<{ run: string; app: string }> => {

let aToken:string;
let bToken:string;
Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      aToken = responses[0];
      bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });

// add this return
return {
    run: aToken ,
    app: bToken
};

)}

Now I’ve created function to call it and get the tokens

async function main() {

    let val = await FetchData();
    console.log(val)

}

The problem is that I got empty value in the val property, while put a breakpoint inside main function
I see that I got into the console, before I actually get the values from the ).then(axios.spread(( ,
Any idea how to adopt the code to return the value from the spread operator and then call to the console?


问:
How to insert a titles row into a csv file
I have a .csv file which has data but not the column headers. I can able to create new .csv file with oldcsv file's content. But I need to add column headers in first row and from second row the existing data should appear.

Here is the code I have written:

```<code> Dim ioFile As New System.IO.StreamReader("C:\sample.csv")
 Dim ioLine As String      Dim ioLines As String
 ioLine = ioFile.ReadLine
 ioLines = ioLine
 While Not ioLine = ""
    ioLine = ioFile.ReadLine
    ioLines = ioLines & vbCrLf & ioLine
 End While
 Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")
 ioWriter.WriteLine(ioLines)
 ioFile.Close()
 ioWriter.Close()
</code>```

Now i need to add column headers in new.csv as "ID","Name","Number","Amount"

答:
```<code>    Using ioFile As New System.IO.StreamReader("C:\sample.csv"), ioWriter As New System.IO.StreamWriter("C:\new.csv")

        ioWriter.WriteLine("ID,Name,Number,Amount")

        Do Until ioFile.Peek = -1

            ioWriter.WriteLine(ioFile.ReadLine)

        Loop

        ioFile.Close()
        ioWriter.Close()

    End Using
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a .csv file which has data but not the column headers. I can able to create new .csv file with oldcsv file's content. But I need to add column headers in first row and from second row the existing data should appear.

Here is the code I have written:

 Dim ioFile As New System.IO.StreamReader("C:\sample.csv")
 Dim ioLine As String      Dim ioLines As String
 ioLine = ioFile.ReadLine
 ioLines = ioLine
 While Not ioLine = ""
    ioLine = ioFile.ReadLine
    ioLines = ioLines & vbCrLf & ioLine
 End While
 Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")
 ioWriter.WriteLine(ioLines)
 ioFile.Close()
 ioWriter.Close()

Now i need to add column headers in new.csv as "ID","Name","Number","Amount"


问:
Bash directory variable error
In a bash script I get to this point

```<code>read ENE CX CY CZ <<< $(head -n 1 RESULTS_${lach}tal2)
echo $ENE
SED_ARG="-e 's/-/m/g'"
read CX2 <<< $( echo ${CX} | eval sed "$SED_ARG")
read CY2 <<< $( echo ${CY} | eval sed "$SED_ARG")
read CZ2 <<< $( echo ${CZ} | eval sed "$SED_ARG")
DIREC="${CX2}_${CY2}_${CZ2}"
echo $DIREC
cd "$DIREC"
</code>```

the value of variable DIREC is the name of a directory and I get things like

```<code>m25.1240_m22.1250_m5.1540
</code>```

this directory does exist, and if I do directly in bash cd m25.1240_m22.1250_m5.1540 it works and I can get inside. But on the script it does not work and I get the error:

```<code>: No such file or directory: cd: m25.1240_m22.1250_m5.1540
</code>```

I do not understand why the error

PS:

```<code>echo "$DIREC" | od -c
</code>```

gives

```<code>0000000   m   2   5   .   1   2   4   0   _   m   2   2   .   1   2   5
0000020   0   _   m   5   .   1   5   4   0  \r  \n
0000033
</code>```

答:
I suspect that inside the script, your working directory is elsewhere, thus you cannot cd. Try this: instead of

```<code>cd "$DIREC"
</code>```

replace it with

```<code>echo current directory is $PWD
cd "m25.1240_m22.1250_m5.1540"
</code>```

and see if you still have the same problem.

Title: Bash directory variable error

Body:
In a bash script I get to this point

read ENE CX CY CZ <<< $(head -n 1 RESULTS_${lach}tal2)
echo $ENE
SED_ARG="-e 's/-/m/g'"
read CX2 <<< $( echo ${CX} | eval sed "$SED_ARG")
read CY2 <<< $( echo ${CY} | eval sed "$SED_ARG")
read CZ2 <<< $( echo ${CZ} | eval sed "$SED_ARG")
DIREC="${CX2}_${CY2}_${CZ2}"
echo $DIREC
cd "$DIREC"

the value of variable DIREC is the name of a directory and I get things like

m25.1240_m22.1250_m5.1540

this directory does exist, and if I do directly in bash cd m25.1240_m22.1250_m5.1540 it works and I can get inside. But on the script it does not work and I get the error:

: No such file or directory: cd: m25.1240_m22.1250_m5.1540

I do not understand why the error

PS:

echo "$DIREC" | od -c

gives

0000000   m   2   5   .   1   2   4   0   _   m   2   2   .   1   2   5
0000020   0   _   m   5   .   1   5   4   0  \r  \n
0000033

Body:
I suspect that inside the script, your working directory is elsewhere, thus you cannot cd. Try this: instead of

cd "$DIREC"

replace it with

echo current directory is $PWD
cd "m25.1240_m22.1250_m5.1540"

and see if you still have the same problem.


问:
Kotlin: passing data from fragment to recyclerview
I have a recyclerview with products that are loaded in trough my API. When you click on a product you get send to the info page where there is a button that adds that product to a new recyclerview. But I have no idea how to send that product to my 'wishlist' recyclerview.
Link to the project: https://github.com/arfeen14/arfeenShopApp

Fragment where the list of products are loaded in from the API.

```<code>`
class DashboardFragment : Fragment() {
    private lateinit var dashboardViewModel: DashboardViewModel
    private lateinit var notificationsViewModel: NotificationsViewModel

    private val popularProducts = arrayListOf<Producten>()
    private val popularProductsAdapter =
        MainProductAdapter(popularProducts, onClickListener = this::clickOnPopularProduct)

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        dashboardViewModel =
            ViewModelProviders.of(requireActivity())[DashboardViewModel::class.java]
        val root = inflater.inflate(R.layout.fragment_dashboard, container, false)

        val rvPopularProducten: RecyclerView = root.findViewById(R.id.rvPopularProducts)
        //rv van category
        val rvCategory: RecyclerView = root.findViewById(R.id.rvCategories)

        // connect the adapters to the recyclerviews
        rvPopularProducten.layoutManager =
            LinearLayoutManager(this.context, LinearLayoutManager.HORIZONTAL, false)
        rvPopularProducten.adapter = popularProductsAdapter

        loadData()

        return root
    }

    fun loadData() {
        dashboardViewModel.getProducts()
        popularProducts.clear()

        dashboardViewModel.product.observe(
            viewLifecycleOwner,
            Observer {
                this.popularProducts.clear()
                popularProducts.addAll(it.products)
                popularProductsAdapter.notifyDataSetChanged()
            })
    }

    private fun clickOnPopularProduct(view: View, product: Producten) {
        val transaction = requireFragmentManager().beginTransaction()
        val productInfoFragment = ProductInfoFragment()

        productInfoFragment.geselecteerdeProduct = product

        transaction.replace(R.id.nav_host_fragment, productInfoFragment)
        transaction.addToBackStack(null)
        transaction.commit()

    }
}
</code>```

This is where the product info is showed when you click on a product.

```<code> class ProductInfoFragment : Fragment() {

    private lateinit var productInfoViewModel: ProductInfoViewModel
    var geselecteerdeProduct: Producten? = null

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        productInfoViewModel = ViewModelProviders.of(this).get(ProductInfoViewModel::class.java)

        val root = inflater.inflate(R.layout.product_info, container, false)

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            root.tvProducInfo_info.text =
                Html.fromHtml(geselecteerdeProduct!!.bodyHtml, Html.FROM_HTML_MODE_LEGACY)
        } else {
            root.tvProducInfo_info.text = Html.fromHtml(geselecteerdeProduct!!.bodyHtml)
        }

        Glide.with(root.context).load(geselecteerdeProduct!!.imagePath.productImgPath)
            .into(root.imgProduct_info)
        root.tvProduct_info_name.text = "€ " + geselecteerdeProduct!!.variants[0].productPrice

        root.btnAddToWishList.setOnClickListener() {
            click()

        }
        return root
    }

    private fun click() {

    }
}
</code>```

The recyclerview where I want my product if you clicked the addToWishListbtn.

```<code>class NotificationsFragment : Fragment() {

    private lateinit var notificationsViewModel: NotificationsViewModel
    val product = arrayListOf<Producten>()

    private val wenslijstAdapter =
        WenslijstAdapter(product)

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        notificationsViewModel =
            ViewModelProviders.of(requireActivity())[NotificationsViewModel::class.java]

        val root = inflater.inflate(R.layout.fragment_notifications, container, false)
        val rvWenslijst: RecyclerView = root.findViewById(R.id.rvWenslijst1)

        rvWenslijst.layoutManager =
            LinearLayoutManager(this.context, LinearLayoutManager.VERTICAL, false)
        rvWenslijst.adapter = wenslijstAdapter

        return root
    }

}
</code>```

答:
You can pass the item in arguments as below:

```<code>   private fun clickOnPopularProduct(view: View, product: Producten) {
    val transaction = requireFragmentManager().beginTransaction()
    val productInfoFragment = ProductInfoFragment()

    **//(psuedocode)
    val bundle = Bundle()
    bundle.putExtra(“product”, //pass your product item here)
    productInfoFragment.arguments = bundle**

    transaction.replace(R.id.nav_host_fragment, productInfoFragment)
    transaction.addToBackStack(null)
    transaction.commit()

}
</code>```

In onCreateView of your ProductInfoFragment you can call after inflating layout:

```<code>override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    productInfoViewModel = ViewModelProviders.of(this).get(ProductInfoViewModel::class.java)

    getArgs()

    val root = inflater.inflate(R.layout.product_info, container, false)

    …
     return root
}

private fun getArgs() {

  //here you can extract your extra(psedocode)
  geselecteerdeProduct = arguments?.getExtra(“product")
}
</code>```

Similarly in this method:

```<code>private fun click() {

}
</code>```

You should pass the product in arguments to the next fragment.

Body:
I have a recyclerview with products that are loaded in trough my API. When you click on a product you get send to the info page where there is a button that adds that product to a new recyclerview. But I have no idea how to send that product to my 'wishlist' recyclerview.
Link to the project: https://github.com/arfeen14/arfeenShopApp

Fragment where the list of products are loaded in from the API.

`
class DashboardFragment : Fragment() {
    private lateinit var dashboardViewModel: DashboardViewModel
    private lateinit var notificationsViewModel: NotificationsViewModel

    private val popularProducts = arrayListOf<Producten>()
    private val popularProductsAdapter =
        MainProductAdapter(popularProducts, onClickListener = this::clickOnPopularProduct)

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        dashboardViewModel =
            ViewModelProviders.of(requireActivity())[DashboardViewModel::class.java]
        val root = inflater.inflate(R.layout.fragment_dashboard, container, false)

        val rvPopularProducten: RecyclerView = root.findViewById(R.id.rvPopularProducts)
        //rv van category
        val rvCategory: RecyclerView = root.findViewById(R.id.rvCategories)

        // connect the adapters to the recyclerviews
        rvPopularProducten.layoutManager =
            LinearLayoutManager(this.context, LinearLayoutManager.HORIZONTAL, false)
        rvPopularProducten.adapter = popularProductsAdapter

        loadData()

        return root
    }

    fun loadData() {
        dashboardViewModel.getProducts()
        popularProducts.clear()

        dashboardViewModel.product.observe(
            viewLifecycleOwner,
            Observer {
                this.popularProducts.clear()
                popularProducts.addAll(it.products)
                popularProductsAdapter.notifyDataSetChanged()
            })
    }

    private fun clickOnPopularProduct(view: View, product: Producten) {
        val transaction = requireFragmentManager().beginTransaction()
        val productInfoFragment = ProductInfoFragment()

        productInfoFragment.geselecteerdeProduct = product

        transaction.replace(R.id.nav_host_fragment, productInfoFragment)
        transaction.addToBackStack(null)
        transaction.commit()

    }
}

This is where the product info is showed when you click on a product.

 class ProductInfoFragment : Fragment() {

    private lateinit var productInfoViewModel: ProductInfoViewModel
    var geselecteerdeProduct: Producten? = null

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        productInfoViewModel = ViewModelProviders.of(this).get(ProductInfoViewModel::class.java)

        val root = inflater.inflate(R.layout.product_info, container, false)

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            root.tvProducInfo_info.text =
                Html.fromHtml(geselecteerdeProduct!!.bodyHtml, Html.FROM_HTML_MODE_LEGACY)
        } else {
            root.tvProducInfo_info.text = Html.fromHtml(geselecteerdeProduct!!.bodyHtml)
        }

        Glide.with(root.context).load(geselecteerdeProduct!!.imagePath.productImgPath)
            .into(root.imgProduct_info)
        root.tvProduct_info_name.text = "€ " + geselecteerdeProduct!!.variants[0].productPrice

        root.btnAddToWishList.setOnClickListener() {
            click()

        }
        return root
    }

    private fun click() {

    }
}

The recyclerview where I want my product if you clicked the addToWishListbtn.

class NotificationsFragment : Fragment() {

    private lateinit var notificationsViewModel: NotificationsViewModel
    val product = arrayListOf<Producten>()

    private val wenslijstAdapter =
        WenslijstAdapter(product)

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        notificationsViewModel =
            ViewModelProviders.of(requireActivity())[NotificationsViewModel::class.java]

        val root = inflater.inflate(R.layout.fragment_notifications, container, false)
        val rvWenslijst: RecyclerView = root.findViewById(R.id.rvWenslijst1)

        rvWenslijst.layoutManager =
            LinearLayoutManager(this.context, LinearLayoutManager.VERTICAL, false)
        rvWenslijst.adapter = wenslijstAdapter

        return root
    }

}

Body:
You can pass the item in arguments as below:

   private fun clickOnPopularProduct(view: View, product: Producten) {
    val transaction = requireFragmentManager().beginTransaction()
    val productInfoFragment = ProductInfoFragment()

    **//(psuedocode)
    val bundle = Bundle()
    bundle.putExtra(“product”, //pass your product item here)
    productInfoFragment.arguments = bundle**

    transaction.replace(R.id.nav_host_fragment, productInfoFragment)
    transaction.addToBackStack(null)
    transaction.commit()

}

In onCreateView of your ProductInfoFragment you can call after inflating layout:

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    productInfoViewModel = ViewModelProviders.of(this).get(ProductInfoViewModel::class.java)

    getArgs()

    val root = inflater.inflate(R.layout.product_info, container, false)

    …
     return root
}

private fun getArgs() {

  //here you can extract your extra(psedocode)
  geselecteerdeProduct = arguments?.getExtra(“product")
}

Similarly in this method:

private fun click() {

}

You should pass the product in arguments to the next fragment.


问:
AspNet Core SignalR and Redux Configuration - send and receive data
I'm implametantion a chat feature that use AspNet Core SiginalR and React.js + Redux.

Steps to problem

I can send the message by signalR for back-end server

I can receive the message back on Middleware

But I cound't dispatch for update de state in store and update views.

Question

What I'm doing wrong ?

Maybe I can not access dispatch function from callback connection.on("ReceiveMessage", data => ...

is it ? How to fix it ?

App

    import '@fake-db'
    import React, {Suspense} from 'react';
    import {FuseAuthorization, FuseLayout, FuseTheme} from '@fuse';
    import Provider from 'react-redux/es/components/Provider';
    import {Router} from 'react-router-dom';
    import jssExtend from 'jss-extend';
    import history from '@history';
    import {Auth} from './auth';
    import store from './store';
    import AppContext from './AppContext';
    import routes from './fuse-configs/routesConfig';
    import {create} from 'jss';
    import {StylesProvider, jssPreset, createGenerateClassName} from '@material-ui/styles';
    import axios from 'axios';

    const jss = create({
        ...jssPreset(),
        plugins       : [...jssPreset().plugins, jssExtend()],
        insertionPoint: document.getElementById('jss-insertion-point'),
    });

    axios.defaults.baseURL = 'https://localhost:5001/api/v1/';

    const generateClassName = createGenerateClassName();

    const App = () => {
        return (
            <Suspense fallback="loading">
                <AppContext.Provider value={{routes}}>

                </AppContext.Provider>
            </Suspense>
        );
    };

    export default App;

```

<p>Create Store   </p>

<pre class="lang-js prettyprint-override"><code>
    import * as reduxModule from 'redux';
    import {applyMiddleware, compose, createStore} from 'redux';
    import createReducer from './reducers';
    import signalRMiddleware from './middlewares/signalRMiddleware';
    import thunk from 'redux-thunk';

    /*
    Fix for Firefox redux dev tools extension
    https://github.com/zalmoxisus/redux-devtools-instrument/pull/19#issuecomment-400637274
     */
    reduxModule.__DO_NOT_USE__ActionTypes.REPLACE = '@@redux/INIT';

    const composeEnhancers =
        process.env.NODE_ENV !== 'production' &&
        typeof window === 'object' &&
        window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
            window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
                // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
            }) : compose;

    const enhancer = composeEnhancers(
        applyMiddleware(
            thunk,
            signalRMiddleware
            )
        // other store enhancers if any
    );

    const store = createStore(createReducer(), enhancer);

    store.asyncReducers = {};

    export const injectReducer = (key, reducer) => {
        if ( store.asyncReducers[key] )
        {
            return;
        }
        store.asyncReducers[key] = reducer;
        store.replaceReducer(createReducer(store.asyncReducers));
        return store;
    };

    export default store;
</code>```

Middleware File

    import { HubConnectionBuilder, LogLevel } from '@microsoft/signalr';
    import * as Actions from "../../main/apps/chat/store/actions";

    const connection = new HubConnectionBuilder().withUrl("https://localhost:5001/chatHub")
                                            .configureLogging(LogLevel.Information)
                                            .withAutomaticReconnect()
                                            .build();

    connection.start();

    export default function signalRMiddleware() {

            connection.on('ReceiveMessage', data => {
                Actions.receiveSocketMessage(data)
            })

            return  next => action => {

            switch (action.type) {

                case Actions.DIRECT_MESSAGE:
                    connection.invoke('DirectMessage', action.payload);
            }

            return next(action);
        }
    }

```

<p>Actions of Chat   </p>

<pre class="lang-js prettyprint-override"><code>
    import axios from 'axios';
    import {setselectedContactId} from './contacts.actions';
    import {closeMobileChatsSidebar} from './sidebars.actions';

    export const GET_CHAT = '[CHAT APP] GET CHAT';
    export const REMOVE_CHAT = '[CHAT APP] REMOVE CHAT';
    export const SEND_MESSAGE = '[CHAT APP] SEND MESSAGE';
    export const DIRECT_MESSAGE = '[CHAT APP] DIRECT MESSAGE';
    export const RECEIVE_MESSAGE = '[CHAT APP] RECEIVE MESSAGE';

    export function receiveSocketMessage(data)
    {
        return (dispatch) => {
            dispatch({type: RECEIVE_MESSAGE, payload: `test`})
        }
    }

    export function directMessage(data)
    {
        return {
            type : DIRECT_MESSAGE,
            payload : data
        }
    }

</code>```

Chat Reducers

    import * as Actions from '../actions';

    const initialState = null;

    const chat = function (state = initialState, action) {
        switch ( action.type )
        {
            case Actions.RECEIVE_MESSAGE:
            {
                return {
                    ...state,
                    directMessage: action.payload
                }
            }
            default:
            {
                return state;
            }
        }
    };

    export default chat;
```

<p>Chat Component   </p>

<pre class="lang-js prettyprint-override"><code>
    import React, {useEffect} from 'react';
    import {useTranslation} from 'react-i18next';
    import {Drawer, AppBar, Toolbar, Typography, IconButton, Hidden, Avatar, Icon, Paper, Button} from '@material-ui/core';
    import {fade} from '@material-ui/core/styles/colorManipulator';
    import {useDispatch, useSelector} from 'react-redux';
    import clsx from 'clsx';
    import withReducer from 'app/store/withReducer';
    import * as Actions from "./store/actions";
    import Chat from "./Chat";
    import ChatsSidebar from "./ChatsSidebar";
    import StatusIcon from "./StatusIcon";
    import ContactSidebar from './ContactSidebar';
    import UserSidebar from './UserSidebar';
    import reducer from './store/reducers';
    import {makeStyles} from '@material-ui/styles';

    const drawerWidth = 400;
    const headerHeight = 200;

    const useStyles = makeStyles(theme => ({
        root              : {
            display        : 'flex',
            flexDirection  : 'row',
            minHeight      : '100%',
            position       : 'relative',
            flex           : '1 1 auto',
            height         : 'auto',
            backgroundColor: theme.palette.background.default
        },
        topBg             : {
            position       : 'absolute',
            left           : 0,
            right          : 0,
            top            : 0,
            height         : headerHeight,
            backgroundImage: 'url("../../assets/images/backgrounds/header-bg.png")',
            backgroundColor: theme.palette.primary.dark,
            backgroundSize : 'cover',
            pointerEvents  : 'none'
        },
        contentCardWrapper: {
            position                      : 'relative',
            padding                       : 24,
            maxWidth                      : 1400,
            display                       : 'flex',
            flexDirection                 : 'column',
            flex                          : '1 0 auto',
            width                         : '100%',
            minWidth                      : '0',
            maxHeight                     : '95%',
            margin                        : '0 auto',
            [theme.breakpoints.down('sm')]: {
                padding: 16
            },
            [theme.breakpoints.down('xs')]: {
                padding: 12
            }
        },
        contentCard       : {
            display        : 'flex',
            position       : 'relative',
            flex           : '1 1 100%',
            flexDirection  : 'row',
            backgroundColor: "f7f7f7",
            boxShadow      : theme.shadows[1],
            borderRadius   : 8,
            minHeight      : 0,
            overflow       : 'hidden'
        },
        drawerPaper       : {
            width                       : drawerWidth,
            maxWidth                    : '100%',
            overflow                    : 'hidden',
            height                      : '100%',
            [theme.breakpoints.up('md')]: {
                position: 'relative'
            }
        },
        contentWrapper    : {
            display      : 'flex',
            flexDirection: 'column',
            flex         : '1 1 100%',
            zIndex       : 10,
            background   : `linear-gradient(to bottom, ${fade(theme.palette.background.paper, 0.8)} 0,${fade(theme.palette.background.paper, 0.6)} 20%,${fade(theme.palette.background.paper, 0.8)})`
        },
        content           : {
            display  : 'flex',
            flex     : '1 1 100%',
            minHeight: 0
        }
    }));

    function ChatApp(props)
    {

        const { t } = useTranslation();
        const dispatch = useDispatch();
        const chat = useSelector(({chatApp}) => chatApp.chat);
        const contacts = useSelector(({chatApp}) => chatApp.contacts.entities);
        const selectedContactId = useSelector(({chatApp}) => chatApp.contacts.selectedContactId);
        const mobileChatsSidebarOpen = useSelector(({chatApp}) => chatApp.sidebars.mobileChatsSidebarOpen);
        const userSidebarOpen = useSelector(({chatApp}) => chatApp.sidebars.userSidebarOpen);
        const contactSidebarOpen = useSelector(({chatApp}) => chatApp.sidebars.contactSidebarOpen);
        const directMessage = useSelector(({chatApp}) => chatApp.directMessage);

        const classes = useStyles(props);
        const selectedContact = contacts.find(_contact => (_contact.id === selectedContactId));

        useEffect(() => {
            dispatch(Actions.getUserData());
            dispatch(Actions.getContacts());
            dispatch(Actions.directMessage({message: "123 testando...", to: "Carlos"}));
        }, [dispatch]);

        useEffect(() => {
            console.log(`Mensagem recebido: ${directMessage} TAMO NO APP`);
        }, [directMessage])

        return (
            <div className={clsx(classes.root)}>

                <div className={clsx(classes.contentCardWrapper, 'container')}>

                    <div className={classes.contentCard}>

                        <Hidden mdUp>
                            <Drawer
                                className="h-full absolute z-20"
                                variant="temporary"
                                anchor="left"
                                open={mobileChatsSidebarOpen}
                                onClose={() => dispatch(Actions.closeMobileChatsSidebar())}
                                classes={{
                                    paper: clsx(classes.drawerPaper, "absolute left-0")
                                }}
                                style={{position: 'absolute'}}
                                ModalProps={{
                                    keepMounted  : true,
                                    disablePortal: true,
                                    BackdropProps: {
                                        classes: {
                                            root: "absolute"
                                        }
                                    }
                                }}
                            >
                                <ChatsSidebar/>
                            </Drawer>
                        </Hidden>
                        <Hidden smDown>
                            <Drawer
                                className="h-full z-20"
                                variant="permanent"
                                open
                                classes={{
                                    paper: classes.drawerPaper
                                }}
                            >
                                <ChatsSidebar/>
                            </Drawer>
                        </Hidden>
                        <Drawer
                            className="h-full absolute z-30"
                            variant="temporary"
                            anchor="left"
                            open={userSidebarOpen}
                            onClose={() => dispatch(Actions.closeUserSidebar())}
                            classes={{
                                paper: clsx(classes.drawerPaper, "absolute left-0")
                            }}
                            style={{position: 'absolute'}}
                            ModalProps={{
                                keepMounted  : false,
                                disablePortal: true,
                                BackdropProps: {
                                    classes: {
                                        root: "absolute"
                                    }
                                }
                            }}
                        >
                            <UserSidebar/>
                        </Drawer>

                        <main className={clsx(classes.contentWrapper, "z-10")}>
                            {!chat ?
                                (
                                    <>
                                        <AppBar position="static" elevation={1}>
                                            <Toolbar className="px-16"/>
                                        </AppBar>
                                        <div className="flex flex-col flex-1 items-center justify-center p-24">
                                            <Paper className="rounded-full p-48">
                                                <Icon className="block text-64" color="secondary">chat</Icon>
                                            </Paper>
                                            <Typography variant="h6" className="my-24">{t("Chat")}</Typography>
                                            <Typography className="hidden md:flex px-16 pb-24 mt-24 text-center" color="textSecondary">
                                                {t("Select a contact to start a conversation!")}
                                            </Typography>
                                            <Button variant="outlined" color="primary" className="flex md:hidden normal-case" onClick={() => dispatch(Actions.openMobileChatsSidebar())}>
                                                {t("Select a contact to start a conversation!")}
                                            </Button>
                                        </div>
                                    </>
                                ) : (
                                    <>
                                        <AppBar position="static" elevation={1}>
                                            <Toolbar className="px-16">
                                                <IconButton
                                                    color="inherit"
                                                    aria-label="Open drawer"
                                                    onClick={() => dispatch(Actions.openMobileChatsSidebar())}
                                                    className="flex md:hidden"
                                                >
                                                    <Icon>chat</Icon>
                                                </IconButton>
                                                <div className="flex items-center cursor-pointer" onClick={() => dispatch(Actions.openContactSidebar())}>
                                                    <div className="relative ml-8 mr-12">
                                                        <div className="absolute right-0 bottom-0 -m-4 z-10">
                                                            <StatusIcon status={selectedContact.status}/>
                                                        </div>

                                                        <Avatar src={selectedContact.avatar} alt={selectedContact.name}>
                                                            {!selectedContact.avatar || selectedContact.avatar === '' ? selectedContact.name[0] : ''}
                                                        </Avatar>
                                                    </div>
                                                    <Typography color="inherit" className="text-18 font-600">{selectedContact.name}</Typography>
                                                </div>
                                            </Toolbar>
                                        </AppBar>

                                        <div className={classes.content}>
                                            <Chat className="flex flex-1 z-10"/>
                                        </div>
                                    </>
                                )
                            }
                        </main>

                        <Drawer
                            className="h-full absolute z-30"
                            variant="temporary"
                            anchor="right"
                            open={contactSidebarOpen}
                            onClose={() => dispatch(Actions.closeContactSidebar())}
                            classes={{
                                paper: clsx(classes.drawerPaper, "absolute right-0")
                            }}
                            style={{position: 'absolute'}}
                            ModalProps={{
                                keepMounted  : true,
                                disablePortal: true,
                                BackdropProps: {
                                    classes: {
                                        root: "absolute"
                                    }
                                }
                            }}
                        >
                            <ContactSidebar/>
                        </Drawer>
                    </div>
                </div>
            </div>
        );
    }

    export default withReducer('chatApp', reducer)(ChatApp);
</code>```

Codesandbox.io

https://codesandbox.io/s/signalr-core-and-redux-v7gp4

答:
you are calling the action creator, but you are not actually dispatching the action it generates in your middleware, so it just creates an object that does nothing.</p>

```<code>-    export default function signalRMiddleware() {
+    export default function signalRMiddleware(api) {

            connection.on('ReceiveMessage', data => {
-                Actions.receiveSocketMessage(data)
+                api.dispatch(Actions.receiveSocketMessage(data))
            })

            return  next => action => {

            switch (action.type) {

                case Actions.DIRECT_MESSAGE:
                    connection.invoke('DirectMessage', action.payload);
            }

            return next(action);
        }
    }
</code>```

Body:
I'm implametantion a chat feature that use AspNet Core SiginalR and React.js + Redux.

Steps to problem

I can send the message by signalR for back-end server

I can receive the message back on Middleware

But I cound't dispatch for update de state in store and update views.

Question

What I'm doing wrong ?

Maybe I can not access dispatch function from callback connection.on("ReceiveMessage", data => ...

is it ? How to fix it ?

App

    import '@fake-db'
    import React, {Suspense} from 'react';
    import {FuseAuthorization, FuseLayout, FuseTheme} from '@fuse';
    import Provider from 'react-redux/es/components/Provider';
    import {Router} from 'react-router-dom';
    import jssExtend from 'jss-extend';
    import history from '@history';
    import {Auth} from './auth';
    import store from './store';
    import AppContext from './AppContext';
    import routes from './fuse-configs/routesConfig';
    import {create} from 'jss';
    import {StylesProvider, jssPreset, createGenerateClassName} from '@material-ui/styles';
    import axios from 'axios';

    const jss = create({
        ...jssPreset(),
        plugins       : [...jssPreset().plugins, jssExtend()],
        insertionPoint: document.getElementById('jss-insertion-point'),
    });

    axios.defaults.baseURL = 'https://localhost:5001/api/v1/';

    const generateClassName = createGenerateClassName();

    const App = () => {
        return (
            <Suspense fallback="loading">
                <AppContext.Provider value={{routes}}>

                </AppContext.Provider>
            </Suspense>
        );
    };

    export default App;

Create Store

    import * as reduxModule from 'redux';
    import {applyMiddleware, compose, createStore} from 'redux';
    import createReducer from './reducers';
    import signalRMiddleware from './middlewares/signalRMiddleware';
    import thunk from 'redux-thunk';

    /*
    Fix for Firefox redux dev tools extension
    https://github.com/zalmoxisus/redux-devtools-instrument/pull/19#issuecomment-400637274
     */
    reduxModule.__DO_NOT_USE__ActionTypes.REPLACE = '@@redux/INIT';

    const composeEnhancers =
        process.env.NODE_ENV !== 'production' &&
        typeof window === 'object' &&
        window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
            window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
                // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
            }) : compose;

    const enhancer = composeEnhancers(
        applyMiddleware(
            thunk,
            signalRMiddleware
            )
        // other store enhancers if any
    );

    const store = createStore(createReducer(), enhancer);

    store.asyncReducers = {};

    export const injectReducer = (key, reducer) => {
        if ( store.asyncReducers[key] )
        {
            return;
        }
        store.asyncReducers[key] = reducer;
        store.replaceReducer(createReducer(store.asyncReducers));
        return store;
    };

    export default store;

Middleware File

    import { HubConnectionBuilder, LogLevel } from '@microsoft/signalr';
    import * as Actions from "../../main/apps/chat/store/actions";

    const connection = new HubConnectionBuilder().withUrl("https://localhost:5001/chatHub")
                                            .configureLogging(LogLevel.Information)
                                            .withAutomaticReconnect()
                                            .build();

    connection.start();

    export default function signalRMiddleware() {

            connection.on('ReceiveMessage', data => {
                Actions.receiveSocketMessage(data)
            })

            return  next => action => {

            switch (action.type) {

                case Actions.DIRECT_MESSAGE:
                    connection.invoke('DirectMessage', action.payload);
            }

            return next(action);
        }
    }

Actions of Chat

    import axios from 'axios';
    import {setselectedContactId} from './contacts.actions';
    import {closeMobileChatsSidebar} from './sidebars.actions';

    export const GET_CHAT = '[CHAT APP] GET CHAT';
    export const REMOVE_CHAT = '[CHAT APP] REMOVE CHAT';
    export const SEND_MESSAGE = '[CHAT APP] SEND MESSAGE';
    export const DIRECT_MESSAGE = '[CHAT APP] DIRECT MESSAGE';
    export const RECEIVE_MESSAGE = '[CHAT APP] RECEIVE MESSAGE';

    export function receiveSocketMessage(data)
    {
        return (dispatch) => {
            dispatch({type: RECEIVE_MESSAGE, payload: `test`})
        }
    }

    export function directMessage(data)
    {
        return {
            type : DIRECT_MESSAGE,
            payload : data
        }
    }

Chat Reducers

    import * as Actions from '../actions';

    const initialState = null;

    const chat = function (state = initialState, action) {
        switch ( action.type )
        {
            case Actions.RECEIVE_MESSAGE:
            {
                return {
                    ...state,
                    directMessage: action.payload
                }
            }
            default:
            {
                return state;
            }
        }
    };

    export default chat;

Chat Component

    import React, {useEffect} from 'react';
    import {useTranslation} from 'react-i18next';
    import {Drawer, AppBar, Toolbar, Typography, IconButton, Hidden, Avatar, Icon, Paper, Button} from '@material-ui/core';
    import {fade} from '@material-ui/core/styles/colorManipulator';
    import {useDispatch, useSelector} from 'react-redux';
    import clsx from 'clsx';
    import withReducer from 'app/store/withReducer';
    import * as Actions from "./store/actions";
    import Chat from "./Chat";
    import ChatsSidebar from "./ChatsSidebar";
    import StatusIcon from "./StatusIcon";
    import ContactSidebar from './ContactSidebar';
    import UserSidebar from './UserSidebar';
    import reducer from './store/reducers';
    import {makeStyles} from '@material-ui/styles';

    const drawerWidth = 400;
    const headerHeight = 200;

    const useStyles = makeStyles(theme => ({
        root              : {
            display        : 'flex',
            flexDirection  : 'row',
            minHeight      : '100%',
            position       : 'relative',
            flex           : '1 1 auto',
            height         : 'auto',
            backgroundColor: theme.palette.background.default
        },
        topBg             : {
            position       : 'absolute',
            left           : 0,
            right          : 0,
            top            : 0,
            height         : headerHeight,
            backgroundImage: 'url("../../assets/images/backgrounds/header-bg.png")',
            backgroundColor: theme.palette.primary.dark,
            backgroundSize : 'cover',
            pointerEvents  : 'none'
        },
        contentCardWrapper: {
            position                      : 'relative',
            padding                       : 24,
            maxWidth                      : 1400,
            display                       : 'flex',
            flexDirection                 : 'column',
            flex                          : '1 0 auto',
            width                         : '100%',
            minWidth                      : '0',
            maxHeight                     : '95%',
            margin                        : '0 auto',
            [theme.breakpoints.down('sm')]: {
                padding: 16
            },
            [theme.breakpoints.down('xs')]: {
                padding: 12
            }
        },
        contentCard       : {
            display        : 'flex',
            position       : 'relative',
            flex           : '1 1 100%',
            flexDirection  : 'row',
            backgroundColor: "f7f7f7",
            boxShadow      : theme.shadows[1],
            borderRadius   : 8,
            minHeight      : 0,
            overflow       : 'hidden'
        },
        drawerPaper       : {
            width                       : drawerWidth,
            maxWidth                    : '100%',
            overflow                    : 'hidden',
            height                      : '100%',
            [theme.breakpoints.up('md')]: {
                position: 'relative'
            }
        },
        contentWrapper    : {
            display      : 'flex',
            flexDirection: 'column',
            flex         : '1 1 100%',
            zIndex       : 10,
            background   : `linear-gradient(to bottom, ${fade(theme.palette.background.paper, 0.8)} 0,${fade(theme.palette.background.paper, 0.6)} 20%,${fade(theme.palette.background.paper, 0.8)})`
        },
        content           : {
            display  : 'flex',
            flex     : '1 1 100%',
            minHeight: 0
        }
    }));

    function ChatApp(props)
    {

        const { t } = useTranslation();
        const dispatch = useDispatch();
        const chat = useSelector(({chatApp}) => chatApp.chat);
        const contacts = useSelector(({chatApp}) => chatApp.contacts.entities);
        const selectedContactId = useSelector(({chatApp}) => chatApp.contacts.selectedContactId);
        const mobileChatsSidebarOpen = useSelector(({chatApp}) => chatApp.sidebars.mobileChatsSidebarOpen);
        const userSidebarOpen = useSelector(({chatApp}) => chatApp.sidebars.userSidebarOpen);
        const contactSidebarOpen = useSelector(({chatApp}) => chatApp.sidebars.contactSidebarOpen);
        const directMessage = useSelector(({chatApp}) => chatApp.directMessage);

        const classes = useStyles(props);
        const selectedContact = contacts.find(_contact => (_contact.id === selectedContactId));

        useEffect(() => {
            dispatch(Actions.getUserData());
            dispatch(Actions.getContacts());
            dispatch(Actions.directMessage({message: "123 testando...", to: "Carlos"}));
        }, [dispatch]);

        useEffect(() => {
            console.log(`Mensagem recebido: ${directMessage} TAMO NO APP`);
        }, [directMessage])

        return (

                        <Hidden mdUp>
                            <Drawer
                                className="h-full absolute z-20"
                                variant="temporary"
                                anchor="left"
                                open={mobileChatsSidebarOpen}
                                onClose={() => dispatch(Actions.closeMobileChatsSidebar())}
                                classes={{
                                    paper: clsx(classes.drawerPaper, "absolute left-0")
                                }}
                                style={{position: 'absolute'}}
                                ModalProps={{
                                    keepMounted  : true,
                                    disablePortal: true,
                                    BackdropProps: {
                                        classes: {
                                            root: "absolute"
                                        }
                                    }
                                }}
                            >
                                <ChatsSidebar/>
                            </Drawer>
                        </Hidden>
                        <Hidden smDown>
                            <Drawer
                                className="h-full z-20"
                                variant="permanent"
                                open
                                classes={{
                                    paper: classes.drawerPaper
                                }}
                            >
                                <ChatsSidebar/>
                            </Drawer>
                        </Hidden>
                        <Drawer
                            className="h-full absolute z-30"
                            variant="temporary"
                            anchor="left"
                            open={userSidebarOpen}
                            onClose={() => dispatch(Actions.closeUserSidebar())}
                            classes={{
                                paper: clsx(classes.drawerPaper, "absolute left-0")
                            }}
                            style={{position: 'absolute'}}
                            ModalProps={{
                                keepMounted  : false,
                                disablePortal: true,
                                BackdropProps: {
                                    classes: {
                                        root: "absolute"
                                    }
                                }
                            }}
                        >
                            <UserSidebar/>
                        </Drawer>

                            {!chat ?
                                (
                                    <>
                                        <AppBar position="static" elevation={1}>
                                            <Toolbar className="px-16"/>
                                        </AppBar>

                                            <Paper className="rounded-full p-48">
                                                <Icon className="block text-64" color="secondary">chat</Icon>
                                            </Paper>
                                            <Typography variant="h6" className="my-24">{t("Chat")}</Typography>
                                            <Typography className="hidden md:flex px-16 pb-24 mt-24 text-center" color="textSecondary">
                                                {t("Select a contact to start a conversation!")}
                                            </Typography>
                                            <Button variant="outlined" color="primary" className="flex md:hidden normal-case" onClick={() => dispatch(Actions.openMobileChatsSidebar())}>
                                                {t("Select a contact to start a conversation!")}
                                            </Button>

                                    </>
                                ) : (
                                    <>
                                        <AppBar position="static" elevation={1}>
                                            <Toolbar className="px-16">
                                                <IconButton
                                                    color="inherit"
                                                    aria-label="Open drawer"
                                                    onClick={() => dispatch(Actions.openMobileChatsSidebar())}
                                                    className="flex md:hidden"
                                                >
                                                    <Icon>chat</Icon>
                                                </IconButton>

 dispatch(Actions.openContactSidebar())}>

                                                            <StatusIcon status={selectedContact.status}/>

                                                        <Avatar src={selectedContact.avatar} alt={selectedContact.name}>
                                                            {!selectedContact.avatar || selectedContact.avatar === '' ? selectedContact.name[0] : ''}
                                                        </Avatar>

                                                    <Typography color="inherit" className="text-18 font-600">{selectedContact.name}</Typography>

                                            </Toolbar>
                                        </AppBar>

                                            <Chat className="flex flex-1 z-10"/>

                                    </>
                                )
                            }

                        <Drawer
                            className="h-full absolute z-30"
                            variant="temporary"
                            anchor="right"
                            open={contactSidebarOpen}
                            onClose={() => dispatch(Actions.closeContactSidebar())}
                            classes={{
                                paper: clsx(classes.drawerPaper, "absolute right-0")
                            }}
                            style={{position: 'absolute'}}
                            ModalProps={{
                                keepMounted  : true,
                                disablePortal: true,
                                BackdropProps: {
                                    classes: {
                                        root: "absolute"
                                    }
                                }
                            }}
                        >
                            <ContactSidebar/>
                        </Drawer>

        );
    }

    export default withReducer('chatApp', reducer)(ChatApp);

Codesandbox.io

https://codesandbox.io/s/signalr-core-and-redux-v7gp4

Body:
you are calling the action creator, but you are not actually dispatching the action it generates in your middleware, so it just creates an object that does nothing.

-    export default function signalRMiddleware() {
+    export default function signalRMiddleware(api) {

            connection.on('ReceiveMessage', data => {
-                Actions.receiveSocketMessage(data)
+                api.dispatch(Actions.receiveSocketMessage(data))
            })

            return  next => action => {

            switch (action.type) {

                case Actions.DIRECT_MESSAGE:
                    connection.invoke('DirectMessage', action.payload);
            }

            return next(action);
        }
    }


问:
Route redirecting to an external link caught in a loop in react router
From a react application i am calling an external link with react router as below

```<code><PrivateRoute exact path='/a/b' component={() => {
                        window.location = `https://externallink/a/b`;
                        return null;
                    }}/>
</code>```

The redirection is working but it is caught in a loop. It calls the external link indefinitely. How can I stop the loop.

答:
Try this  </p>

```<code><PrivateRoute exact path='/a/b' component={() => {
                        useEffect(()=>{
                        const redirectLink = `https://externallink/a/b`
                        window.location !== redirectLink
                        && window.location = redirectLink
                        },[])
                        return null;
                    }}/>
</code>```

Body:
From a react application i am calling an external link with react router as below

<PrivateRoute exact path='/a/b' component={() => {
                        window.location = `https://externallink/a/b`;
                        return null;
                    }}/>

The redirection is working but it is caught in a loop. It calls the external link indefinitely. How can I stop the loop.

Body:
Try this

<PrivateRoute exact path='/a/b' component={() => {
                        useEffect(()=>{
                        const redirectLink = `https://externallink/a/b`
                        window.location !== redirectLink
                        && window.location = redirectLink
                        },[])
                        return null;
                    }}/>


问:
Put a select in a variable
I would like to add a select with information from the database and save it in a variable. Unfortunately it doesn't work for me, it just shows me one record and not all records.

$sql = $conn->query("SELECT * FROM recaudacionBancaria")
foreach ($sql as $key => $value) {
    // class='theClass' value='".$value['cuenta']."'idCuenta='".$value['id']."'>
";
    $cuenta = "
<select  class='form-control input-xs cue' name='cue' id='cue'>
                <option>'".$value['cuenta']."'</option>
                $cat= $conn->query("SELECT * FROM bancos");

                foreach ($cat as $key => $val) {
                    '<option value="'.$val["cuenta"].'">'.$val["cuenta"].'</option>';
                }
                </select>
";
    echo '

    '.$value['subsistema'].'
    '.$cajas.'

';
```

答:
Try this:

Replace your code with this.

$cat= $conn->query("SELECT * FROM bancos");
while($row = $cat->fetch_assoc()) {
 '<option value="'.$row["cuenta"].'">'.$row["cuenta"].'</option>';
}

```

Title: Put a select in a variable